Compare commits

...
39 Commits
Author SHA1 Message Date
Radosław Smoliński 12fbd424a5 1.12.3
CI / check (push) Canceled after 0s
2026-10-21 18:16:31 +02:00
Radosław SmolińskiandClaude Opus 5.5 6b4336f961 Detailed cookie settings window (CookieBanner settings="detailed")
A third settings mode next to 'inline' and 'modal': a large dialog where every consent
category is a card with its on/off control, description and an expandable list of the
cookies it covers (name, provider, purpose, duration), taken from Cookie Settings → Cookies
— the same rows as <CookieTable>. The developer picks the mode with one prop; the
component default stays 'inline', so existing sites are unchanged.

Cookie Settings gets a localized detailLabels group (list labels, English fallback);
getConsentTexts passes texts.cookies and texts.details, sharing the row mapping with
getCookieTable. New classNames slots and data-ipal handles for the cards and lists.

Docs for devs and agents: consent.md (modes compared, which to pick — new projects default
to 'detailed' when the cookie list is filled), AGENT.md, PROGRAMISTA §2.8/§2.11/§6, skills
ipal-setup, ipal-site, ipal-upgrade, ipal-locale-add, ipal-consent-check. Postgres/SQLite
projects need migrate:create for the new fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 18:16:30 +02:00
Radosław Smoliński 1413e96731 1.12.2
CI / check (push) Canceled after 0s
2026-10-21 16:45:03 +02:00
Radosław SmolińskiandClaude Opus 5.5 e1431a7c49 Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration
buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:45:03 +02:00
Radosław Smoliński 2c3195c4e1 1.12.1
CI / check (push) Canceled after 0s
2026-10-21 15:11:04 +02:00
Radosław SmolińskiandClaude Opus 5.5 4ec27d9ef0 Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet
Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.

Also in this release: meta.description auto-filled from page blocks, <NoSnippet>,
MetaDescriptionCheck in the SEO tab, data-nosnippet on banner/language switcher, GA4 CSP
wildcards, consent version passed to Analytics' default consent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 15:10:55 +02:00
Radosław Smoliński 305c564d13 1.12.0
CI / check (push) Canceled after 0s
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 166bf51e53 Lazy 404: createNotFoundPage({ load }) + renderNotFoundView, NotFoundLoader
Next puts a layout's not-found tree into the RSC payload of every page under it. The eager
createNotFoundPage({ blocks }) rendered the panel's 404 page there in every locale, so with
404 = homepage each page shipped the homepage twice (homepage HTML 195 -> 146 KB gzip).
With { load } only <NotFoundLoader> is in the payload; the content comes from the project's
server action (renderNotFoundView, locale checked against configured locales) when a 404 shows.
The eager variant is unchanged. Docs: pages.md, i18n.md, AGENT.md, PROGRAMISTA, ipal-setup, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 8b35986635 1.11.1
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 faa4ad679c Theme switcher, table of contents, missing-page redirect, form placeholders and time field; audit and revalidate fixes
- buildRevalidateHook skips outside Next (no NEXT_RUNTIME) and with context.disableRevalidate
- BuilderForm focuses only on a real step change (no scroll to the form on remount)
- mediaImageProps: placeholder colour only for JPEG (placeholderColor); hook stores no colour for transparent images
- buildLinkField: interface name per shape (CmsLink, CmsLinkPlain, CmsLinkNoLabel) + interfaceName option
- Cookie Settings: buttons.save -> buttons.savePreferences (Mongoose reserved name)
- ThemeScript, ThemeSwitcher, useTheme; Site Settings defaultTheme 'system' + themeToggleLabel; Turnstile follows page theme
- extractHeadings, RenderRichText headingIds, TableOfContents, buildTableOfContentsField
- createPageRoute onMissing: 'redirectHome'
- Form builder: localized placeholder on text/email/textarea/number, new time field
- ipal-audit: no false positive for object keys between JSX elements; /md route not reported as dynamic

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 23e033d7d7 1.11.0
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00
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
Radosław Smoliński 46d30d4ecd 1.10.1
CI / check (push) Canceled after 0s
2026-10-19 00:07:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 a6eda2e3a3 Pass siteDescription to page metadata; document media cache rule
createPageMetadata read Site Settings → siteDescription but never passed it to
buildMetadata, so pages without their own meta description had no
<meta name="description"> or og:description. Regression test in seo.test.ts.

storage.md: Cloudflare Cache Rule for the media domain (R2 objects carry no
Cache-Control; storage-s3 cannot set it, Cloudflare defaults to 4 h).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 00:07:28 +02:00
radoslaw.smolinski d28cbe2570 1.10.0
CI / check (push) Canceled after 0s
2026-10-17 03:20:12 +02:00
radoslaw.smolinskiandClaude Opus 5.5 2bd9d60822 Cookie banner layout options; keep admin UI out of /client
CookieBanner: order, settings="modal", controls="switch",
settingsActions, icon and a class slot for every element. Cookie
Settings gains eyebrow, title, settingsDescription, alwaysActiveLabel
and buttons.close.

MaskedField, TestEmailButton and IntegrationStatusBanner import
@payloadcms/ui and moved from /client to /admin; with sideEffects in
package.json the site bundle no longer ships ~235 KB gz of admin code.
A test walks the /client import graph to keep it that way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 03:20:11 +02:00
radoslaw.smolinski 0f6a43ad12 1.9.9
CI / check (push) Canceled after 0s
2026-10-17 01:29:01 +02:00
radoslaw.smolinskiandClaude Opus 5.5 14d71bcc3a Readable form emails (forms.emailLayout)
{{*:table}} renders a readable submission summary (questions, option labels,
grouped by step, empty fields skipped) inside an email template with logo,
accent colour and footer from Site Settings → Emails. submitForm stores the
submission in the page language, so emails follow the visitor's locale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 01:29:00 +02:00
radoslaw.smolinski 78e4e0f8e6 1.9.8
CI / check (push) Canceled after 0s
2026-10-16 22:15:57 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8f8b79d003 Under construction mode (developer tool)
Site Settings -> Under construction: a switch, 'Pages still available' and
notice texts. When on, only the homepage and the chosen pages open (every
language); other addresses redirect to the homepage with the notice
(createPageRoute redirect option), and <ConstructionNotice> cancels clicks
on links to blocked pages and shows the notice. getConstructionMode(locale).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:15:57 +02:00
radoslaw.smolinski 91d5e986c5 1.9.7
CI / check (push) Canceled after 0s
2026-10-16 20:53:26 +02:00
radoslaw.smolinskiandClaude Opus 5.5 080086adfe Forms: conditional fields and steps (Show only when)
Every form block (built-in, Checkbox group, Step, message) gets a showWhen
group: visible only when another field has one of the given values. A hidden
Step drops out with its fields; browser and server share visibleFields, so a
hidden field is neither required nor stored. GDPR consent is always enforced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 20:53:25 +02:00
radoslaw.smolinski 8c1a8b0e8e 1.9.6
CI / check (push) Canceled after 0s
2026-10-16 13:51:33 +02:00
radoslaw.smolinskiandClaude Opus 5.5 002eef56d1 Changelog 1.9.6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:51:31 +02:00
radoslaw.smolinskiandClaude Opus 5.5 924b5cf8be Markdown route: type-safe locale code read
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:42:17 +02:00
radoslaw.smolinski 3e17f92af1 1.9.5
CI / check (push) Canceled after 0s
2026-10-16 13:32:34 +02:00
radoslaw.smolinskiandClaude Opus 5.5 c83d2dec0c Merge 1.9.5: single-language Markdown route
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:32:31 +02:00
radoslaw.smolinskiandClaude Opus 5.5 df0f5e03c3 Single-language sites: Markdown route without the locale param; i18n docs corrected
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:32:31 +02:00
radoslaw.smolinski 67e8da6ec3 1.9.4
CI / check (push) Canceled after 0s
2026-10-16 13:11:10 +02:00
radoslaw.smolinskiandClaude Opus 5.5 191cf44361 Merge 1.9.4: link styles, system links, audit rules
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:11:08 +02:00
radoslaw.smolinskiandClaude Opus 5.5 6a0fefdbae Project-defined link styles, legal links from System Pages; audit catches content-keyed logic, Polish text in code, link fields in globals
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:11:08 +02:00
radoslaw.smolinski 0069b28941 1.9.3
CI / check (push) Canceled after 0s
2026-10-16 12:56:14 +02:00
radoslaw.smolinskiandClaude Opus 5.5 3da9d6b1d0 Merge 1.9.3: audit catches hand-rolled links
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 12:56:13 +02:00
radoslaw.smolinskiandClaude Opus 5.5 eb52253dc4 Audit: catch hand-rolled link resolution (hardcoded homepage slug, URL built from a slug); comment filter fix
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 12:56:13 +02:00
radoslaw.smolinski f88c342be5 1.9.2
CI / check (push) Canceled after 0s
2026-10-16 11:52:43 +02:00
radoslaw.smolinskiandClaude Opus 5.5 293cd9a541 Merge 1.9.2: import instead of code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:42 +02:00
radoslaw.smolinskiandClaude Opus 5.5 81e864bde9 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]>
2026-10-16 11:52:29 +02:00
radoslaw.smolinskiandClaude Opus 5.5 412bf953a8 Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them,
  useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text,
  bound action, public part of the form only — the Emails tab never reaches the browser)
- Notifications: next / back / stepOf texts
- createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav,
  resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest)
- /rsc: SiteProviders, createPageRoute, createNotFoundPage
- resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField
- Dev sandbox frontend built on these imports; tests (unit + real Payload)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:32:46 +02:00
radoslaw.smolinskiandClaude Opus 5.5 0cfd846dd1 Changelog: history back to 1.7.4, keep at least 20 versions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:59:38 +02:00
180 changed files with 9679 additions and 941 deletions
@@ -0,0 +1,18 @@
import { notFound, permanentRedirect } from 'next/navigation.js'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../../blocks/FormBlock.js'
import * as content from '../../../../lib/content.js'
import { sendForm } from '../actions.js'
export const revalidate = 3600
const route = createPageRoute(content, {
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
blocks: { formBlock: FormBlock },
notFound,
permanentRedirect,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams
+7
View File
@@ -0,0 +1,7 @@
'use server'
import { headers } from 'next/headers.js'
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { getCachedPayload } from '../../../lib/content.js'
export const sendForm = createSubmitAction({ getCachedPayload, headers })
+22
View File
@@ -0,0 +1,22 @@
import { notFound } from 'next/navigation.js'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '../../../lib/content.js'
import './styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
<main>{children}</main>
</SiteProviders>
</body>
</html>
)
}
@@ -0,0 +1,6 @@
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../blocks/FormBlock.js'
import * as content from '../../../lib/content.js'
export default createNotFoundPage(content, { blocks: { formBlock: FormBlock }, fallback: <h1>404</h1> })
+10
View File
@@ -0,0 +1,10 @@
/* Sandbox look — in a project this is the design system. */
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 40rem; padding: 1rem; }
.grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); }
.field { grid-column: span 2; } .half { grid-column: span 1; }
.label, legend { display: block; font-weight: 600; margin-bottom: .25rem; }
.input { border: 1px solid #999; border-radius: 6px; box-sizing: border-box; padding: .5rem; width: 100%; }
.choices { border: 0; display: grid; gap: .25rem; margin: 0; padding: 0; } .choice { display: flex; gap: .5rem; }
.error { color: #b00020; } .progress { color: #555; } .step-title { font-size: 1.25rem; font-weight: 700; }
.actions { display: flex; gap: .5rem; margin-top: 1rem; } .btn { background: #111; border: 0; border-radius: 6px; color: #fff; padding: .6rem 1rem; }
.btn-secondary { background: #ddd; color: #111; } .success { background: #e7f7ec; padding: 1rem; }
+60 -6
View File
@@ -1,12 +1,39 @@
import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { IntegrationStatusBanner as IntegrationStatusBanner_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { MaskedField as MaskedField_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { TestEmailButton as TestEmailButton_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { RscEntryLexicalCell as RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { RscEntryLexicalField as RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { LexicalDiffComponent as LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { InlineToolbarFeatureClient as InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HorizontalRuleFeatureClient as HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UploadFeatureClient as UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BlockquoteFeatureClient as BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { RelationshipFeatureClient as RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { LinkFeatureClient as LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ChecklistFeatureClient as ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { OrderedListFeatureClient as OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnorderedListFeatureClient as UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { IndentFeatureClient as IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { AlignFeatureClient as AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HeadingFeatureClient as HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ParagraphFeatureClient as ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { InlineCodeFeatureClient as InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SuperscriptFeatureClient as SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SubscriptFeatureClient as SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
/** @type import('payload').ImportMap */
@@ -14,11 +41,38 @@ export const importMap = {
"@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/admin#MetaDescriptionCheck": MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/client#IntegrationStatusBanner": IntegrationStatusBanner_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#MaskedField": MaskedField_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#TestEmailButton": TestEmailButton_630f031911beff97691b963f10a20a86,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalCell": RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalField": RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#LexicalDiffComponent": LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/client#InlineToolbarFeatureClient": InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HorizontalRuleFeatureClient": HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UploadFeatureClient": UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BlockquoteFeatureClient": BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#RelationshipFeatureClient": RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#LinkFeatureClient": LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ChecklistFeatureClient": ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#OrderedListFeatureClient": OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnorderedListFeatureClient": UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#IndentFeatureClient": IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#AlignFeatureClient": AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HeadingFeatureClient": HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ParagraphFeatureClient": ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#InlineCodeFeatureClient": InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SuperscriptFeatureClient": SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SubscriptFeatureClient": SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#StrikethroughFeatureClient": StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}
+2
View File
@@ -0,0 +1,2 @@
export { mcpGET as GET, mcpPOST as POST } from '../../../lib/content.js'
export const dynamic = 'force-dynamic'
+2
View File
@@ -0,0 +1,2 @@
export { llmsRoute as GET } from '../../lib/content.js'
export const dynamic = 'force-dynamic'
+16
View File
@@ -0,0 +1,16 @@
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
// Classes set once per project — here plain names the sandbox CSS styles.
const formClasses = {
actions: 'actions', back: 'btn btn-secondary', choice: 'choice', choices: 'choices', error: 'error', field: 'field',
fieldHalf: 'half', fields: 'grid', form: 'form', formError: 'error', input: 'input', label: 'label', progress: 'progress',
select: 'input', stepTitle: 'step-title', submit: 'btn', success: 'success', textarea: 'input',
}
type Props = { form?: unknown; formTexts?: FormNotificationTexts; locale: string; sendForm?: SendFormAction }
export function FormBlock({ form, formTexts, locale, sendForm }: Props) {
if (!formTexts || !sendForm) return null
return <RenderForm action={sendForm} classNames={formClasses} form={form as never} locale={locale} requiredMark=" *" texts={formTexts} />
}
+7
View File
@@ -0,0 +1,7 @@
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const
+11
View File
@@ -0,0 +1,11 @@
// Sandbox data layer — the same one line every project has (PROGRAMISTA §2.7).
import config from '@payload-config'
import { createContentHelpers } from '@intecion/ipal-kit'
import { i18nConfig } from '../i18n.config.js'
export const {
generatePageMetadata, generateStaticParams, getCachedPayload, getConfiguredLocales, getFormTexts, getLinkOptions,
getNotFoundPage, getPageJsonLd, getSettings, getSiteShell, healthRoute, i18n, llmsRoute, mcpGET, mcpPOST,
resolveNav, resolvePageRedirect, resolveRoute,
} = createContentHelpers({ baseUrl: 'http://localhost:3000', config, i18n: i18nConfig, mcp: { serverName: 'ipal-sandbox' } })
+543 -44
View File
@@ -73,6 +73,7 @@ export interface Config {
media: Media;
forms: Form;
'form-submissions': FormSubmission;
'consent-records': ConsentRecord;
'payload-kv': PayloadKv;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
@@ -86,6 +87,7 @@ export interface Config {
media: MediaSelect<false> | MediaSelect<true>;
forms: FormsSelect<false> | FormsSelect<true>;
'form-submissions': FormSubmissionsSelect<false> | FormSubmissionsSelect<true>;
'consent-records': ConsentRecordsSelect<false> | ConsentRecordsSelect<true>;
'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
@@ -172,46 +174,15 @@ export interface User {
export interface Page {
id: number;
title?: string | null;
meta?: {
title?: string | null;
description?: string | null;
/**
* Maximum upload file size: 12MB. Recommended file size for images is <500KB.
*/
image?: (number | null) | Media;
/**
* Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.
*/
titleOverride?: string | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media".
*/
export interface Media {
id: number;
updatedAt: string;
createdAt: string;
url?: string | null;
thumbnailURL?: string | null;
filename?: string | null;
mimeType?: string | null;
filesize?: number | null;
width?: number | null;
height?: number | null;
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "posts".
*/
export interface Post {
id: number;
title?: string | null;
slug?: string | null;
layout?:
| {
form?: (number | null) | Form;
id?: string | null;
blockName?: string | null;
blockType: 'formBlock';
}[]
| null;
meta?: {
title?: string | null;
description?: string | null;
@@ -242,6 +213,19 @@ export interface Form {
width?: number | null;
required?: boolean | null;
defaultValue?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'checkbox';
@@ -260,6 +244,23 @@ export interface Form {
label?: string | null;
width?: number | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'email';
@@ -280,6 +281,19 @@ export interface Form {
};
[k: string]: unknown;
} | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'message';
@@ -290,6 +304,23 @@ export interface Form {
width?: number | null;
defaultValue?: number | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'number';
@@ -308,6 +339,19 @@ export interface Form {
}[]
| null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'select';
@@ -327,6 +371,23 @@ export interface Form {
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'text';
@@ -337,10 +398,168 @@ export interface Form {
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'textarea';
}
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
/**
* Empty = no minimum (Required = at least one).
*/
minSelected?: number | null;
/**
* Empty = no limit.
*/
maxSelected?: number | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'checkboxGroup';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
defaultValue?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'date';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'radio';
}
| {
/**
* Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.
*/
title?: string | null;
description?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'step';
}
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'time';
}
)[]
| null;
submitButtonLabel?: string | null;
@@ -392,6 +611,46 @@ export interface Form {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media".
*/
export interface Media {
id: number;
updatedAt: string;
createdAt: string;
url?: string | null;
thumbnailURL?: string | null;
filename?: string | null;
mimeType?: string | null;
filesize?: number | null;
width?: number | null;
height?: number | null;
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "posts".
*/
export interface Post {
id: number;
title?: string | null;
meta?: {
title?: string | null;
description?: string | null;
/**
* Maximum upload file size: 12MB. Recommended file size for images is <500KB.
*/
image?: (number | null) | Media;
/**
* Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.
*/
titleOverride?: string | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions".
@@ -409,6 +668,25 @@ export interface FormSubmission {
updatedAt: string;
createdAt: string;
}
/**
* Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records".
*/
export interface ConsentRecord {
id: number;
consentId: string;
version: number;
choices?: {
necessary?: boolean | null;
functional?: boolean | null;
analytics?: boolean | null;
marketing?: boolean | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv".
@@ -456,6 +734,10 @@ export interface PayloadLockedDocument {
| ({
relationTo: 'form-submissions';
value: number | FormSubmission;
} | null)
| ({
relationTo: 'consent-records';
value: number | ConsentRecord;
} | null);
globalSlug?: string | null;
user: {
@@ -529,6 +811,18 @@ export interface UsersSelect<T extends boolean = true> {
*/
export interface PagesSelect<T extends boolean = true> {
title?: T;
slug?: T;
layout?:
| T
| {
formBlock?:
| T
| {
form?: T;
id?: T;
blockName?: T;
};
};
meta?:
| T
| {
@@ -591,6 +885,12 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
required?: T;
defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -611,6 +911,13 @@ export interface FormsSelect<T extends boolean = true> {
label?: T;
width?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -618,6 +925,12 @@ export interface FormsSelect<T extends boolean = true> {
| T
| {
message?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -629,6 +942,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -648,6 +968,12 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
};
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -669,6 +995,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -680,6 +1013,109 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
checkboxGroup?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
minSelected?: T;
maxSelected?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
date?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
radio?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
step?:
| T
| {
title?: T;
description?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
time?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -723,6 +1159,24 @@ export interface FormSubmissionsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records_select".
*/
export interface ConsentRecordsSelect<T extends boolean = true> {
consentId?: T;
version?: T;
choices?:
| T
| {
necessary?: T;
functional?: T;
analytics?: T;
marketing?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv_select".
@@ -807,13 +1261,17 @@ export interface SiteSetting {
*/
favicon?: (number | null) | Media;
/**
* Theme applied on a visitor’s first visit.
* Theme applied on a visitor’s first visit. System = the visitor’s device setting.
*/
defaultTheme: 'light' | 'dark';
defaultTheme: 'light' | 'dark' | 'system';
/**
* Show a light/dark switch on the site.
*/
allowThemeToggle?: boolean | null;
/**
* Name of the switch read by screen readers, e.g. "Dark mode".
*/
themeToggleLabel?: string | null;
updatedAt?: string | null;
createdAt?: string | null;
}
@@ -908,6 +1366,14 @@ export interface CookieSetting {
* Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.
*/
policyVersion: number;
/**
* Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.
*/
eyebrow?: string | null;
/**
* Banner heading, e.g. "We respect your privacy". Empty → not shown.
*/
title?: string | null;
/**
* Main consent message shown in the banner.
*/
@@ -916,6 +1382,14 @@ export interface CookieSetting {
* Heading for the detailed settings panel.
*/
settingsTitle?: string | null;
/**
* Intro under the settings heading — what cookies are for and that the choice can be changed later.
*/
settingsDescription?: string | null;
/**
* Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.
*/
alwaysActiveLabel?: string | null;
/**
* Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.
*/
@@ -927,8 +1401,12 @@ export interface CookieSetting {
acceptAll?: string | null;
reject?: string | null;
settings?: string | null;
save?: string | null;
savePreferences?: string | null;
back?: string | null;
/**
* Screen-reader label of the ✕ button in the settings dialog.
*/
close?: string | null;
};
/**
* Per-category titles and descriptions.
@@ -986,6 +1464,18 @@ export interface Notification {
*/
consent?: string | null;
notFound?: string | null;
/**
* Step-by-step forms: button to the next step.
*/
next?: string | null;
/**
* Step-by-step forms: button to the previous step.
*/
back?: string | null;
/**
* Progress — {current} and {total} are replaced.
*/
stepOf?: string | null;
};
updatedAt?: string | null;
createdAt?: string | null;
@@ -1010,6 +1500,7 @@ export interface SiteSettingsSelect<T extends boolean = true> {
favicon?: T;
defaultTheme?: T;
allowThemeToggle?: T;
themeToggleLabel?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
@@ -1063,8 +1554,12 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
*/
export interface CookieSettingsSelect<T extends boolean = true> {
policyVersion?: T;
eyebrow?: T;
title?: T;
message?: T;
settingsTitle?: T;
settingsDescription?: T;
alwaysActiveLabel?: T;
privacyLinkLabel?: T;
buttons?:
| T
@@ -1072,8 +1567,9 @@ export interface CookieSettingsSelect<T extends boolean = true> {
acceptAll?: T;
reject?: T;
settings?: T;
save?: T;
savePreferences?: T;
back?: T;
close?: T;
};
categories?:
| T
@@ -1112,6 +1608,9 @@ export interface NotificationsSelect<T extends boolean = true> {
validation?: T;
consent?: T;
notFound?: T;
next?: T;
back?: T;
stepOf?: T;
};
updatedAt?: T;
createdAt?: T;
+12 -8
View File
@@ -7,6 +7,7 @@ import sharp from 'sharp'
import { fileURLToPath } from 'url'
import { testEmailAdapter } from './helpers/testEmailAdapter.js'
import { i18nConfig } from './i18n.config.js'
import { seed } from './seed.js'
const filename = fileURLToPath(import.meta.url)
@@ -30,7 +31,15 @@ export default buildConfig({
},
{
slug: 'pages',
fields: [{ name: 'title', type: 'text' }],
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: [{ slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms' }] }],
},
],
},
{
slug: 'posts',
@@ -56,16 +65,11 @@ export default buildConfig({
plugins: [
ipalKit({
access: { authCollection: 'users' },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
i18n: i18nConfig,
consentLog: true,
forms: {},
seo: { collections: ['posts', 'pages'] },
stats: true,
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false,
}),
+46
View File
@@ -22,4 +22,50 @@ export const seed = async (payload: Payload) => {
},
})
}
await seedContactPage(payload)
}
const text = (t: string) => ({
root: {
children: [{ children: [{ detail: 0, format: 0, mode: 'normal', style: '', text: t, type: 'text', version: 1 }], direction: null, format: '', indent: 0, type: 'paragraph', version: 1 }],
direction: null,
format: '',
indent: 0,
type: 'root',
version: 1,
},
})
/** A step-by-step quote form on /pl/kontakt — exercises RenderForm, steps, choice lists, dates. */
async function seedContactPage(payload: Payload) {
const { totalDocs } = await payload.count({ collection: 'pages', where: { slug: { equals: 'kontakt' } } })
if (totalDocs) {return}
const form = await payload.create({
collection: 'forms',
data: {
confirmationMessage: text('Dziękujemy! Odezwiemy się w ciągu 24 godzin.'),
confirmationType: 'message',
fields: [
{ blockType: 'step', title: 'Kontakt' },
{ name: 'name', blockType: 'text', label: 'Imię i nazwisko', required: true, width: 50 },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true, width: 50 },
{ blockType: 'step', description: 'Zaznacz, czego potrzebujesz.', title: 'Projekt' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona WWW', value: 'www' }, { label: 'SEO', value: 'seo' }, { label: 'Kampanie', value: 'ads' }], required: true },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'do 10 tys.', value: 's' }, { label: 'powyżej 10 tys.', value: 'l' }], required: true },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ blockType: 'message', message: text('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.') },
{ name: 'consent', blockType: 'checkbox', label: 'Zgadzam się na przetwarzanie danych.', required: true },
],
submitButtonLabel: 'Wyślij zapytanie',
title: 'Wycena',
} as never,
})
const page = await payload.create({
collection: 'pages',
data: { layout: [{ blockType: 'formBlock', form: form.id }], slug: 'kontakt', title: 'Kontakt' } as never,
})
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Sandbox' } as never })
payload.logger.info(`[seed] /pl/kontakt (page ${page.id}, form ${form.id})`)
}
+564
View File
@@ -3,6 +3,384 @@
Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
**ipal-upgrade** i [PROGRAMISTA.md §6](./dev/PROGRAMISTA.md).
Trzymamy tu co najmniej **20 ostatnich wersji** — przy aktualizacji projektu o kilka
wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” od
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20.
## 1.12.3
### Nowe
- **Duże okno ustawień cookies ze szczegółami** — `<CookieBanner settings="detailed" />`. Każda kategoria to karta
z przełącznikiem (wł./wył.), opisem i rozwijaną listą ciasteczek, które obejmuje (nazwa, dostawca, cel, czas) —
z **Cookie Settings → Cookies**. Tryb wybiera programista: `'inline'` (domyślnie, bez zmian), `'modal'`,
`'detailed'`. Nowa grupa w globalu **Cookie Settings → Detail labels** (podpisy listy, per język; puste →
angielskie). `ConsentTexts` ma opcjonalne `cookies` i `details` (wypełnia je `getConsentTexts`). Nowe sloty
`classNames`: `categoryCard`, `cookies`, `cookiesToggle`, `cookieList`, `cookie`, `cookieName`, `cookieMeta`.
consent.md → „Duże okno ze szczegółami”.
### Dokumentacja
- consent.md: porównanie trzech trybów `settings`, który wybrać (brief milczy → `detailed` przy wypełnionej liście
Cookies), nowe pola w tabeli tekstów z panelu, sloty i uchwyty `data-ipal`.
- AGENT.md (§0b poz. 12, §7, compliance), PROGRAMISTA §2.8 / §2.11 / §6 poz. 46, skille `ipal-setup`, `ipal-site`,
`ipal-upgrade`, `ipal-locale-add` (Detail labels i Cookies w każdym języku), `ipal-consent-check` (import zasila
też okno `detailed` — sprawdź je po imporcie).
### Wymaga zmian w projekcie
1. Postgres/SQLite: nowe pola w globalu Cookie Settings → `payload migrate:create`. MongoDB bez zmian.
2. Opcjonalnie: `<CookieBanner settings="detailed" />`, wypełnij Cookie Settings → Cookies (skan:
`ipal-consent-check` → cookie-scan) i Detail labels w każdym języku.
## 1.12.2
### Poprawki
- **Pusty panel admina na produkcji przez import mapę z deva.** `buildR2Storage` bez `R2_*` zwracał no-op, więc
`pnpm dev` / `generate:importmap` bez R2 zapisywał `importMap.js` bez `S3ClientUploadHandler`; projekt to
commitował, a produkcyjny panel (z R2) renderował pustą stronę bez błędu w konsoli. Teraz adapter jest
rejestrowany zawsze (bez R2 jako `enabled: false`, media dalej na dysku) — import mapa jest identyczna w każdym
środowisku. `ipal-audit`: ERROR „import map without the R2 upload handler”.
- **Cookie Settings — tekst „Zapisz” nie ginie po 1.11.1 (MongoDB).** Pierwszy zapis globala usuwał stare
`buttons.save` i przycisk wracał do „Save preferences” we wszystkich językach. Plugin przy starcie kopiuje
`buttons.save` → `buttons.savePreferences` (wszystkie języki), gdy nowego pola brak. `getConsentTexts` czytał stare
pole jako tekst, a Mongo zwraca je jako mapę `{ pl, en }` (pola nie ma w schemacie) — w banerze mogło wyjść
„[object Object]”.
- `ipal-audit`: `"exclude"` w kilku liniach tsconfig nie jest już zgłaszany; `a11y`, `i18n`, `l10n` to nie „numbered
fields”; łapie linki `` `${prefix}/${slug}` `` i ścieżki stron wpisane w kod (`` `${prefix}/kontakt` ``); komunikat
„panel text in Polish — admin labels/descriptions are English” (był mylący „panel is English”).
### Nowe
- **Media tylko do odczytu:** samo `R2_PUBLIC_URL` (absolutne, poza produkcją) → adresy plików z domeny mediów,
upload i usuwanie zablokowane (403). Lokalny dev na bazie produkcyjnej bez kluczy do bucketa. `ipalEnvRules` w
devie nie wymaga wtedy reszty `R2_*`. storage.md → „Zachowanie”.
- **`context: { ipalSkipAutoFill: true }`** (`SKIP_AUTO_FILL`) — zapis bez auto-fill meta i `aiSummary`. Dla migracji
danych i skryptów, które mają zapisać tylko to, co ustawiają. seo.md.
- **`createPageRoute` przekierowuje stronę główną spod jej sluga** (`/pl/home` → 308 `/pl`). Wyłączenie:
`homeAlias: false`. Usuń własne przekierowanie z `page.tsx`. pages.md.
### Dokumentacja
- i18n.md: `fallback: true` utrwala tekst języka domyślnego w pustych polach innych języków przy zapisie — skutki i
jak pisać skrypty.
- PROGRAMISTA §1: `pnpm up --latest @intecion/ipal-kit` (samo `pnpm up` nie wyjdzie poza dokładną wersję); 401 przy
publicznym rejestrze = stary token w `~/.npmrc`.
### Wymaga zmian w projekcie
1. `pnpm up --latest @intecion/ipal-kit`, potem `pnpm payload generate:importmap` i sprawdź, że `importMap.js` ma
`@payloadcms/storage-s3/client#S3ClientUploadHandler` (projekt z `buildR2Storage`). Commituj.
2. Własne przekierowanie strony głównej spod sluga (np. w `render` z `buildLocalizedPath`) — usuń, robi to
`createPageRoute`.
3. Opcjonalnie: lokalny dev na bazie produkcyjnej → w `.env` samo `R2_PUBLIC_URL` zamiast kluczy R2.
## 1.12.1
### Nowe
- **Opis każdej strony z jej treści** — auto-fill wypełnia puste `meta.description` z bloków strony (`layout` →
akapity bez nagłówków, całe zdania do ~155 znaków), gdy `autoFill.description` nic nie daje. Wcześniej strona bez
opisu dostawała `siteDescription` — ten sam na każdej stronie, więc Google go ignorował i cytował stopkę.
`autoFill: { content: 'blocks' | false, descriptionLength }`. Opis wpisany ręcznie nigdy nie jest nadpisywany.
- **`<NoSnippet>`** (`/rsc`, `/client`) — `data-nosnippet` na `div`/`section`/`span`. Dla stopki, paska kontaktowego,
powtarzanego CTA: Google przestaje pokazywać adres i godziny ze stopki jako opis podstron. `CookieBanner` i
`LanguageSwitcher` mają `data-nosnippet` same. Opis: seo.md → „Opisy w Google”.
- **Podpowiedź pod opisem w tabie SEO** (`MetaDescriptionCheck`) — opis pusty, taki sam jak `siteDescription` albo jak
w innym dokumencie kolekcji. Nie blokuje zapisu. `seo.descriptionCheck: { settingsSlug, siteDescriptionField }`
albo `false`.
- **ipal-seo-check** — ostrzeżenia: zduplikowane meta description, stopka bez `data-nosnippet`.
- **Statystyki w panelu** — `ipalKit({ stats: true })` + `<SiteProviders stats={{ locale }}>` (albo `<PageStats>`
z `/client`). Widok `/admin/stats`: wizyty dziennie z 30 dni, strony, wejścia, źródła, urządzenia; wykres na
dashboardzie. Bez cookies i bez zapisu IP — **nie wymaga zgody** (hash z solą wymienianą codziennie). Odwiedzający ze
zgodą *analytics* (ta sama co GA4) dostają cookie `ipal_vid` i historię przez wiele dni; serwer sam sprawdza cookie
zgody. Kolekcja `stats-visits`, retencja 90 dni. Opis + tekst do polityki prywatności: stats.md.
- `@payloadcms/next` w peerDependencies (widok `/admin/stats` używa jego `DefaultTemplate`; każdy projekt Payload+Next
już go ma).
### Poprawki
- **Auto-fill przy częściowym zapisie** — `payload.update` / REST PATCH bez grupy `meta` nie traktuje już zapisanego
tytułu jako pustego (czyta go z dokumentu).
### Wymaga zmian w projekcie
1. `pnpm payload generate:importmap` — nowy komponent panelu `@intecion/ipal-kit/admin#MetaDescriptionCheck`.
2. Stopka: treść w `<NoSnippet>` wewnątrz `<footer>` (nie na `<footer>` — tam Google atrybutu nie honoruje):
`import { NoSnippet } from '@intecion/ipal-kit/rsc'`. To samo dla powtarzanego paska kontaktowego / CTA.
3. Opcjonalnie: istniejące strony bez opisu dostaną go przy najbliższym zapisie. Żeby od razu — zapisz je w panelu.
Projekt bez pola `layout` (bloki pod inną nazwą): `autoFill: { content: '<nazwa pola>' }`.
4. Sprawdzenie: `ipal-seo-check` bez ostrzeżeń o stopce i zduplikowanych opisach; w Search Console → Sprawdź URL
→ poproś o ponowne zindeksowanie głównych stron.
5. Opcjonalnie, statystyki: `stats: true` w `ipalKit`, `stats={{ locale }}` w `<SiteProviders>`,
`pnpm payload generate:importmap`, migracja (Postgres). W panelu Cookie Settings → Cookies dopisz `ipal_vid`
(analytics) i uzupełnij politykę prywatności — gotowy tekst w stats.md.
## 1.12.0
### Nowe
- **Leniwa strona 404** — `createNotFoundPage(content, { load })` + `renderNotFoundView(content, { blocks, blockProps,
fallback }, locale)` (`/rsc`) w server action projektu; `<NotFoundLoader>` (`/client`). Next wkłada drzewo
`not-found` layoutu do danych RSC KAŻDEJ strony; wariant `{ blocks }` renderował tam stronę 404 z panelu w każdym
języku (404 = strona główna, 2 języki: HTML strony głównej 195 → 146 KB gzip, dane RSC −42%). Teraz w danych jest
tylko loader, treść przychodzi przy wyświetleniu 404. `renderNotFoundView` przyjmuje tylko skonfigurowane języki.
Opis: pages.md → „Strona 404”.
### Wymaga zmian w projekcie
Nic obowiązkowego — `createNotFoundPage(content, { blocks })` działa jak dotąd. Zalecane (każdy projekt z 404
z panelu, zwłaszcza 404 = strona główna albo kilka języków):
1. `src/app/(frontend)/[locale]/notFoundView.ts` (`.tsx`, gdy `fallback` to JSX):
`'use server'` + `export async function loadNotFoundView(locale: string) { return renderNotFoundView(content,
{ blocks: blockRegistry, blockProps, fallback }, locale) }` — opcje przenieś z `not-found.tsx`.
2. `not-found.tsx`: `export default createNotFoundPage(content, { load: loadNotFoundView })`.
3. Sprawdzenie: w HTML dowolnej strony brak treści strony 404 (`self.__next_f`), a nieznany adres
(np. `/xx/test`) nadal daje 404 z treścią z panelu.
## 1.11.1
### Nowe
- **Motyw jasny / ciemny** — `<ThemeScript>` (`/rsc`, albo `<SiteProviders theme>`) ustawia `data-theme` i
`color-scheme` na `<html>` przed malowaniem; `<ThemeSwitcher>` bez stylów (`role="switch"`), `useTheme()`,
`applyTheme` (`/client`). Wybór w `localStorage` (`ipal-theme`), synchronizacja kart. Site Settings → Theme:
`defaultTheme: 'system'`, `themeToggleLabel`; `getSiteShell(locale).theme`. Opis: theme.md.
- **Turnstile w motywie strony** — `turnstileTheme` domyślnie `'page'` (bez motywu strony = `'auto'` jak dotąd).
- **Spis treści** — `extractHeadings`, `RenderRichText headingIds` (te same id), `<TableOfContents>` (`/client`,
`aria-current="location"`), `buildTableOfContentsField()`. Opis: richtext.md.
- **Brak strony → strona główna** — `createPageRoute(…, { redirect, onMissing: 'redirectHome' })` albo własna funkcja.
- **Formularze** — pole „Placeholder” (localized) w blokach text, email, textarea, number; nowy typ **Time**
(`HH:MM`, walidowany na serwerze).
- `buildLinkField({ interfaceName })`.
### Poprawki
- **`buildRevalidateHook` poza Next** — bez `NEXT_RUNTIME` (`payload run`, seed, migracje) albo z
`context.disableRevalidate` hook nic nie robi. Wcześniej: `Invariant: static generation store missing`.
- **`BuilderForm` nie przewija strony do formularza** — fokus tylko przy zmianie kroku. Wcześniej React
uruchamiał efekt ponownie (Next przywracający odwiedzoną stronę, StrictMode) i fokus skakał na pierwsze pole.
- **Kolor placeholdera pod przezroczystymi obrazami** — `mediaImageProps` daje `backgroundColor` tylko dla JPEG
(`placeholderColor`), hook nie liczy koloru dla obrazów z alfą. Koniec czarnych prostokątów pod logotypami.
- **Typ linku nie zależy od kolejności pól** — każdy kształt ma własną nazwę: `CmsLink`, `CmsLinkPlain`
(`appearances: false`), `CmsLinkNoLabel`, `CmsLinkPlainNoLabel`. Wszystkie pasują do `CmsLink`.
- **Ostrzeżenie Mongoose przy każdym starcie** — pole Cookie Settings `buttons.save` → `buttons.savePreferences`
(`save` to nazwa zarezerwowana). API frontu bez zmian (`texts.buttons.save`).
- **ipal-audit** — klucze obiektu między elementami JSX (`narrow: <A />, wide: <B />`) nie są już zgłaszane jako
tekst na sztywno; reguła „page routes rendered dynamically” pomija trasę `/md/[locale]` (route handlery są `force-dynamic` z założenia).
### Wymaga zmian w projekcie
- Migracja (Postgres/SQLite): `pnpm payload migrate:create` — nowe pola (placeholder, time, `themeToggleLabel`,
wartość `system`), zmiana nazwy `buttons_save` → `buttons_save_preferences`: gdy drizzle zapyta o kolumnę,
wybierz **rename**; inaczej tekst przycisku wróci do domyślnego „Save preferences” i trzeba go wpisać w panelu.
MongoDB: bez migracji; plugin próbuje odczytać starą wartość, ale sprawdź przycisk „Zapisz” w banerze i w razie
potrzeby wpisz tekst w Cookie Settings → Buttons → Save.
- `pnpm payload generate:types` — linki bez stylu / bez etykiety mają nowe nazwy typów; kod z `CmsLink` działa dalej.
- Usuń obejścia z PROGRAMISTA §6 poz. 38–45 (komentarze `WORKAROUND ipal-kit` w projekcie). `pnpm ipal:skills` (nowy audyt).
## 1.11.0
### Nowe
- **Pola formularza wypełniane przez stronę** — `values` w `RenderForm`, `BuilderForm` i `useBuilderForm`
(`{ subject: 'Pierścionek · białe złoto · 0,70 ct' }`): pole tylko do odczytu (`classNames.fixed`), w SSR,
wysyłane i walidowane jak każde inne. `prepareBuilderForm` (`/rsc`) — serwerowa połowa `RenderForm` dla
komponentu klienckiego ze zmiennymi wartościami (konfigurator); `publicForm` eksportowany. Koniec kopii `publicForm` w projektach.
- **Linki do wpisów kolekcji** — `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })`;
`resolveLinkHref` / `resolveLink` / `resolveNav` budują `/{locale}/{archiwum}/{wpis}`, `getLinkOptions` podaje archiwa z Site Settings.
- **JSON-LD wpisów, które nie są artykułami** — `pageJsonLd.entries` (węzeł per kolekcja) i `buildProductJsonLd`
(`Offer` tylko z prawdziwą ceną).
- **`isFirst`** dla bloków z `createPageRoute` / `createNotFoundPage` — pierwsza sekcja niesie jedyny `h1`.
### Poprawki
- `ipalEnvRules({ storage: true })`: `R2_*` wymagane na produkcji; w dev opcjonalne (media na dysku), ale wszystkie albo żadne.
Wcześniej dev bez R2 nie startował, więc projekty warunkowały `storage` same.
- `buildImagesConfig()`: poza produkcją dopuszcza media serwowane przez aplikację (`/api/media/file/**` na
`NEXT_PUBLIC_SERVER_URL`) i localhost (`dangerouslyAllowLocalIP`) — bez R2 obrazy w dev nie dawały 500.
### Wymaga zmian w projekcie
- Usuń obejścia z PROGRAMISTA §6 poz. 34–37 (kopie `publicForm`, ręczne remotePatterns dla localhost,
warunkowe `storage`, własny graf JSON-LD wpisów).
- Zmiana `relationTo` linku na tablicę zmienia kształt danych istniejących linków — migracja (ipal-migrate-fields).
## 1.10.1
### Poprawki
- **Zapasowy metaopis działa.** `createPageMetadata` (a więc `createPageRoute` / `generatePageMetadata`) czytał
Site Settings → `siteDescription`, ale nie przekazywał go do `buildMetadata` — strona bez własnego
`meta.description` nie miała `<meta name="description">` ani `og:description` (Lighthouse SEO: „Dokument nie
ma metaopisu”). Test regresyjny w `test/seo.test.ts`.
### Dokumentacja
- storage.md → „Pamięć podręczna mediów”: reguła Cache Rules w Cloudflare dla domeny mediów (1 rok). Pliki w R2
nie mają `Cache-Control` (adapter S3 nie pozwala go ustawić), a Cloudflare daje domyślnie 4 h.
### Wymaga zmian w projekcie
- Obejście metaopisu w projekcie (własne uzupełnianie `description` w `generateMetadata`) można usunąć —
wystarczy `export const generateMetadata = route.generateMetadata`.
- Cloudflare: dodaj regułę Cache Rules dla domeny mediów (storage.md).
## 1.10.0
### Nowe
- **Baner cookies pod projekt** — `CookieBanner`: `order` (kolejność przycisków), `settings="modal"` (ustawienia
w oknie na środku: ✕, Escape, klik w tło), `controls="switch"` (przełączniki `role="switch"`),
`settingsActions` (np. Zapisz / Tylko niezbędne / Akceptuj), `icon={false}`; `classNames` ma slot dla każdego
elementu (tekst, każdy przycisk, modal, karta kategorii, przełącznik, znacznik). Cookie Settings: `eyebrow`,
`title`, `settingsDescription`, `alwaysActiveLabel`, `buttons.close`. Opis: consent.md → „Układ”.
### Poprawki
- **`/client` nie wciąga panelu admina do strony.** `MaskedField`, `TestEmailButton`, `IntegrationStatusBanner`
(importują `@payloadcms/ui`) są teraz w `/admin`; `sideEffects` w package.json. Każda strona importująca
cokolwiek z `/client` (CookieBanner, LanguageSwitcher…) ładowała ~235 KB gz kodu panelu. Test pilnuje regresji.
### Wymaga zmian w projekcie
- `pnpm payload generate:importmap` (ścieżki komponentów panelu: `/client#…` → `/admin#…`), `rm -rf .next`.
- Import `MaskedField` / `TestEmailButton` / `IntegrationStatusBanner` z `@intecion/ipal-kit/client` →
`@intecion/ipal-kit/admin`.
- Nowe pola Cookie Settings: Postgres/SQLite → `pnpm payload migrate:create`; MongoDB bez zmian.
## 1.9.9
### Nowe
- **Ładne maile z formularzy** (`forms: { emailLayout: true }`): `{{*:table}}` → czytelne podsumowanie (pytania,
etykiety odpowiedzi, grupy według kroków, bez pustych pól) + szablon maila (logo, kolor akcentu, stopka z
Site Settings → Emails; tabele + inline CSS). Przepustka `forms.beforeEmail`. Opis: forms.md → „Ładne maile”.
### Poprawki
- `submitForm` zapisuje zgłoszenie w języku strony — maile (temat, treść, potwierdzenie) wychodziły zawsze w
języku domyślnym, także dla odwiedzających wersję angielską.
### Wymaga zmian w projekcie
- `emailLayout: true` dodaje pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`).
Ustaw `serverURL` w `buildConfig` (absolutny adres logo i link w mailu).
## 1.9.8
### Nowe
- **Strona w budowie** (narzędzie deweloperskie): Site Settings → Under construction — przełącznik, lista
„Pages still available” i teksty popupu. Gdy włączone, otwiera się tylko strona główna i wybrane strony
(w każdym języku); inne adresy → strona główna z popupem, kliknięcie linku do zablokowanej strony →
popup zamiast przejścia. `createPageRoute(…, { redirect })`, `getConstructionMode(locale)`,
`<ConstructionNotice>` (`/client`). Opis: construction.md.
### Wymaga zmian w projekcie
- Nowe pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`, jeśli projekt ich używa).
Bez `redirect` w `createPageRoute` i bez `<ConstructionNotice>` tryb nie działa (nic się nie zmienia).
## 1.9.7
### Nowe
- **Pola i kroki warunkowe w formularzach z panelu** („Show only when”, `showWhen`): każde pole,
Checkbox group, message i **Step** może pokazywać się tylko przy wybranej odpowiedzi innego pola
(`field` + `values` po przecinku). Ukryty Step wypada z formularza razem z polami, kolejne kroki
się przenumerowują. Przeglądarka i serwer stosują tę samą regułę (`visibleFields`): ukryte pole nie
jest wymagane ani zapisywane; zgoda RODO (`consent`) jest egzekwowana zawsze. Opis: forms.md →
„Pola i kroki warunkowe”.
### Wymaga zmian w projekcie
- Nowa grupa w blokach formularzy = nowe kolumny w bazie. Po aktualizacji: `pnpm payload migrate:create`
(z kompletem `R2_*`, jeśli projekt ich używa) i `pnpm payload migrate`. Istniejące formularze działają
bez zmian (puste „Show only when” = pole zawsze widoczne).
## 1.9.6
### Poprawki
- Trasa Markdown: bezpieczny typ przy odczycie kodów języków z configu (bez zmian w działaniu).
Wydanie zbiorcze — zawiera wszystko z 1.9.2–1.9.5 (formularze krokowe, `SiteProviders`,
`createPageRoute`, trasy z jednej linii, własne style linków, `getSystemLinks`, Markdown na
stronie jednojęzycznej, nowe reguły audytu). Przy aktualizacji ze starszej wersji przejdź sekcje
„Wymaga zmian w projekcie” od swojej wersji w górę.
## 1.9.5
### Poprawki
- **Markdown (GEO) na stronie jednojęzycznej:** `/md/kontakt` szło do trasy `md/[locale]/[[...slug]]`
jako język „kontakt” → 404, a `/md` (strona główna) nie miało trasy. `markdownRoute` /
`createMarkdownRoute` działa teraz bez parametru `locale` (`app/md/[[...slug]]/route.ts`, język z config),
a trasa z `[locale]` na stronie jednojęzycznej czyta ten segment jako slug.
### Dokumentacja
- i18n.md: strona jednojęzyczna na `SiteProviders`, `createPageRoute`, `createNotFoundPage` i
`app/md/[[...slug]]`. Usunięta błędna rada „załóż `[locale]` na zapas przy jednym języku” (linki byłyby
bez `/pl`, strony z `/pl`); opisane przejście na kilka języków (proxy przekieruje stare adresy).
### Wymaga zmian w projekcie
- Strona jednojęzyczna z `app/md/[locale]/[[...slug]]/route.ts` → przenieś plik do `app/md/[[...slug]]/route.ts`
(bez zmian treści), żeby działało `/md` dla strony głównej.
## 1.9.4
### Nowe
- **Style linków z projektu:** `buildLinkField` / `buildLinksField({ appearances })` przyjmują dowolne nazwy
i etykiety panelu — `['primary', { label: 'Highlighted', value: 'highlight' }]`. Wcześniej tylko
primary / secondary / link, co pchało projekty do warunków po treści (`label === 'Tesla'`).
- **Linki prawne:** `getSystemLinks(locale, roles?)` w `lib/content` (i `resolveSystemLinks`) — href i
etykieta (tytuł strony w danym języku) z Site Settings → System Pages.
### Audyt
- ERROR: logika po treści (`label?.toLowerCase() === '…'`), polski tekst w literałach kodu frontu,
pola linków/przycisków w globalach (`prefooterButtonUrl`, `ctaLabel`…); WARNING: relacja do `pages` w
globalu zamiast `buildLinkField`.
### Wymaga zmian w projekcie
- Globale Header/Footer z polami `page` + `url` + `label` → `buildLinkField` (dane trzeba przenieść —
skill **ipal-migrate-fields**), potem `resolveNav` / `resolveLink`; linki prawne → `getSystemLinks`.
## 1.9.3
### Audyt
- `ipal-audit` łapie ręczne liczenie linków pod dowolną nazwą (`resolveHref`, `getHref`…):
slug strony głównej wpisany w kodzie (`=== 'home'`, `'strona-glowna'`) i URL sklejany ze sluga
(`` `/${slug}` ``, `'/' + slug`) — ERROR z odesłaniem do `resolveLink` / `resolveNav`. Taka kopia gubi
prefiks języka, stronę główną z Site Settings, filtr `javascript:` i martwe linki.
- Poprawka: komentarz zaczynający linię nie jest już zgłaszany przez reguły ignorujące komentarze
(mniej fałszywych alarmów).
- AGENT.md (zakazane zamienniki) i links.md: jak przemapować pole `page` + `url` na `resolveLink`.
### Wymaga zmian w projekcie
- Nowe ERROR-y w audycie wskazują własne funkcje linków — zamień na `resolveLink(link, locale)` z `lib/content`
(PROGRAMISTA §6 poz. 33).
## 1.9.2
Import zamiast kodu: to, co każdy projekt pisał tak samo, jest w pluginie — logika i
szkielet. Wygląd zostaje w projekcie (klasy, własny markup na hookach). Wszystko opcjonalne:
dotychczasowy kod projektów działa bez zmian.
### Wymaga zmian w projekcie
- **Bezpieczeństwo — własny `FormRenderer`:** szablon z `ipal-form` przekazywał do komponentu
klienckiego cały dokument formularza. Local API czyta z `overrideAccess`, więc w HTML/RSC
lądowała zakładka **Emails** (adresy firmy, szablony). Zamień blok na `<RenderForm>` (niżej) albo
przekazuj do klienta tylko pola, etykiety i potwierdzenie. PROGRAMISTA §6 poz. 28.
- **Postgres:** `pnpm payload migrate:create` — nowe typy pól formularza (Step, Checkbox group,
Radio, Date) i teksty `next` / `back` / `stepOf` w Notifications. MongoDB/SQLite (push) bez zmian.
### Nowe
- **Formularze z panelu w jednej linii:** `<RenderForm form action locale texts classNames>` (`/rsc`) —
rich text, wiązanie akcji, redirect, tylko publiczna część formularza w przeglądarce. Pod spodem
`BuilderForm` (`/client`, czysty dostępny HTML bez stylów, `classNames`, `renderField`) i
`useBuilderForm` (cała logika dla własnego markupu). Szablony: `ipal-form/resources/FormBlock.tsx`,
`formClasses.ts`, `CustomForm.example.tsx` (stary `FormRenderer.tsx` usunięty).
- **Formularze krokowe i listy wyboru:** w panelu bloki **Step** (podział na ekrany, tytuł i opis per
język), **Checkbox group** (wiele wyborów, min/max), **Radio**, **Date** — domyślnie włączone
(`forms.fields.<typ>: false` wyłącza). Serwer sprawdza wartości z panelu, liczbę wyborów i daty;
wybory zapisane czytelnie („www, seo”). Dalej waliduje bieżący krok, błąd z serwera wraca na krok z
polem, fokus na nowym kroku. Teksty: Notifications → `next`, `back`, `stepOf`.
- **Layout:** `getSiteShell(locale)` (zgoda, analityka, klucz Turnstile, teksty formularzy, JSON-LD
WebSite + Organization, Site Settings) + `<SiteProviders shell>` (`/rsc`) — providery, baner,
przycisk cookies, Analytics, JSON-LD i preconnect w dobrej kolejności; każda część do podmiany
albo wyłączenia. `siteJsonLd` w `createContentHelpers` dla LocalBusiness.
- **Strona i 404:** `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })`
i `createNotFoundPage(content, { blocks, fallback })` (`/rsc`).
- **Trasy z jednej linii:** `createContentHelpers` zwraca `llmsRoute`, `llmsFullRoute`,
`markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`; opcje
`summaryField`, `mcp`, `markdown`, `redirectCollections` raz w `lib/content.ts`.
- **Linki i menu:** `resolveLink` (href, `internal`, `targetProps`, `appearance`), `resolveNav`
(dowolna głębokość, martwe linki pominięte), `homeSlugFrom`; w `lib/content`: `resolveLink(link, locale)`,
`resolveNav(items, locale)`, `getLinkOptions`, `getHomeSlug`, `resolvePageRedirect`, `getFormTexts`.
- **Pola sekcji:** `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds, anchor, fields })`
— ten sam kształt danych co dawne `src/fields/section*.ts` (bez migracji).
- `useOptionalTurnstile()` — bez providera zwraca `enabled: false` zamiast rzucać.
### Dokumentacja i audyt
- AGENT.md §7 to pełny katalog „potrzeba → import”; §0b, §3, §6 i PROGRAMISTA §2.7–2.8, §6
(poz. 28–33) opisują nowy sposób; skille ipal-form, ipal-nav, ipal-block, ipal-setup, ipal-upgrade
zaktualizowane.
- `ipal-audit` przyjmuje trasy-re-eksporty i `SiteProviders`; nowe reguły: kopia silnika formularza,
`src/fields/section*.ts` / `lib/navigation.ts` (WARNING), import roota / `/rsc` / `/server` w
komponencie klienckim (ERROR).
- Test `docsConsistency`: każdy import z dokumentacji istnieje w kodzie, każdy publiczny eksport jest opisany.
- Sandbox (`dev/`) ma front zbudowany na tych importach (formularz krokowy na `/pl/kontakt`).
## 1.9.1
### Wymaga zmian w projekcie
@@ -93,3 +471,189 @@ Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
przy instalacji z gita. CI w `.gitea/workflows/ci.yml`.
- 79 testów (vitest), w tym integracyjne na prawdziwym Payloadzie (SQLite w pamięci).
- `pnpm typecheck`, `pnpm lint` (0 błędów), `pnpm test:int`.
## 1.8.14
### Wymaga zmian w projekcie
- **2FA: w Next `twoFactor.plugin` trzeba wstrzyknąć** (`plugin: payloadTotp`).
`serverExternalPackages` nie jest obejściem — pakiet importuje własne `.css`,
którego Node nie załaduje. Usuń wpis z `next.config` i adapter z rzutowaniem.
### Poprawki
- `collection` w typie 2FA to `CollectionSlug` (wcześniej `string`) —
`plugin: payloadTotp` przechodzi typecheck bez rzutowania (`TS2322`).
- Paczka publikuje `bin` — działa `ipal-skills`.
## 1.8.13
### Nowe
- **Status wysyłki maili w panelu:** `mailAdapter()` zapisuje wynik w Site
Integrations; błąd → alert na dashboardzie i baner w zakładce SMTP. Formularz
działa dalej (zgłoszenie zapisane). Po aktualizacji: `generate:importmap`,
Postgres: `migrate:create`.
- Formularze w panelu w grupie **Forms** z etykietami (`forms.adminGroup`);
Notifications w grupie Settings — bez nadpisań w projekcie.
### Wymaga zmian w projekcie
- **`POST /api/form-submissions` zamknięty dla anonimów** (403). Front wysyła przez
server action + `submitForm` (skill `ipal-form`). Świadomie publiczny REST →
`formSubmissionOverrides.access.create`.
## 1.8.12
### Nowe
- **Turnstile: awaria po naszej stronie nie blokuje formularzy.** `checkTurnstile`
(`/server`) rozróżnia `pass` / `reject` (zły token odwiedzającego) / `degraded`
(brak lub zły sekret, Cloudflare nieosiągalny). `degraded` → zgłoszenie przyjęte,
alert na dashboardzie (`IntegrationAlerts`) i baner w Site Integrations →
Turnstile. Twardo: `submitForm({ turnstileOnConfigError: 'reject' })`.
- Sekret Turnstile z panelu albo env `TURNSTILE_SECRET_KEY`; przyczyna odrzucenia
w logu serwera. `remoteip` domyślnie nie jest wysyłany (`sendRemoteIp: true`).
- Po aktualizacji: `generate:importmap`, Postgres: `migrate:create` (`turnstileStatus`).
## 1.8.11
### Nowe
- Limit zapytań na IP: wyszukiwarka (`createSearchRoute`, 120/min) i MCP
(`createMcpRoute`, 60 wiadomości/min, batch maks. 10) → `429` z `Retry-After`.
`rateLimit: { max, windowMs }` albo `false` (limiter z przodu, np. Cloudflare WAF).
- Wspólny moduł limitera (`shared/rateLimit`) dla formularzy, wyszukiwarki i MCP.
## 1.8.10
### Zmiany
- Nagłówek stylowanej sitemapy to stałe „XML Sitemap” (bez nazwy strony z Site
Settings); usunięta opcja `siteNameField`. Własny tytuł: `sitemapStyle: { title }`.
## 1.8.9
### Nowe
- **`@intecion/ipal-kit/env`** — walidacja env bez Payload i Node, bezpieczna w
`instrumentation.ts` (root paczki wywracał Edge/Turbopack).
- **`fluid.css`** — płynna skala typografii i odstępów 360→1280 px (same zmienne,
opt-in, mapowanie w `@theme`).
- `R2_PUBLIC_URL` poza produkcją może być ścieżką (`/media`) — prefiksowana
`NEXT_PUBLIC_SERVER_URL`; CSP nie dopisuje jej do `img-src`.
- `ipal-audit`: `html-check.mjs` — inline JSON-LD bez escapowania `<` = ERROR (XSS).
### Poprawki
- `createSitemapRouteHandler` wymaga `req` — Next 16 sprawdza typ pierwszego
argumentu route handlera (`Request | undefined` wywracał build).
## 1.8.8
- Przywrócony opcjonalny `req` w handlerze sitemapy (cofnięte w 1.8.9).
## 1.8.7
- Poprawki typów `routeHandlers` (handler sitemapy).
## 1.8.6
### Poprawki
- `buildLinkField` importował `src/…` zamiast ścieżki względnej — błąd w projekcie.
## 1.8.5
### Nowe
- **`sitemapRoute`** z `createContentHelpers`: XML dla crawlerów, a w przeglądarce
wygląd serwowany przez plugin (`/sitemap.xml?style`, CSS na XML, nie XSLT).
`sitemapStyle: { accent, credit, title } | false`.
### Wymaga zmian w projekcie
- Jedna sitemapa: `app/sitemap.xml/route.ts` (`export { sitemapRoute as GET }`);
usuń `app/sitemap.ts` i `public/sitemap.css` (`ipal-audit` to zgłasza).
## 1.8.4
### Nowe
- **`rowLabel()`** (`/admin`) — wiersze tablic w panelu pokazują treść („Kontakt”)
zamiast „Item 01”. Po dodaniu: `generate:importmap`.
- **`buildOptimizeUploadHook`** — optymalizacja obrazów przy uploadzie.
- Skille agenta: `ipal-site` (strona od briefu do raportu), seed treści, `ipal-upgrade` i inne.
- Baner cookies: atrybuty `data-ipal` na przyciskach (testy), etykiety z tekstów panelu.
## 1.8.3
### Nowe
- **Moduł Links:** `buildLinkField`, `buildLinksField`, `resolveLinkHref` — link do
strony / URL / pliku, przyciski sekcji jako tablica (zamiast `cta1`, `cta2`).
- `createContentHelpers`: `generatePageMetadata` (współdzieli cache z trasą) i opcja
`robots`; jeden odczyt Site Settings na język na żądanie.
- Szablony kodu sekcji i nawigacji dla agenta (`ipal-block`, `ipal-nav`).
## 1.8.2
### Poprawki
- Brakujący eksport `LocaleView` w `/client`.
## 1.8.1
### Poprawki
- Przywrócone zmiany z 1.7.14, które wydanie 1.8.0 przypadkiem cofnęło
(`LocaleView`, 404 bez `headers()`, poprawki R2). **Nie używaj 1.8.0.**
## 1.8.0
- Wydanie wadliwe: cofało zmiany z 1.7.14 — zaktualizuj do 1.8.1 lub nowszej.
- Dokumentacja agenta przeniesiona do `docs/agent/AGENT.md` + skille.
## 1.7.14
### Wymaga zmian w projekcie
- **`not-found.tsx` bez `headers()`** — Next 16 zamieniał stronę SSG/ISR na
dynamiczną. Serwer renderuje 404 dla każdego języka, `<LocaleView>` wybiera
wersję z URL (pages.md).
### Poprawki
- `buildR2Storage`: poprawki konfiguracji R2.
- Skille dla agentów (`ipal-audit` i inne).
## 1.7.12
### Nowe
- Link do polityki prywatności w banerze cookies brany automatycznie z Site
Settings → System Pages; tekst linku w panelu (`privacyLinkLabel`, per język).
Stare `privacyPolicy.label` w kodzie — przestarzałe.
- Nowa struktura dokumentacji: `docs/dev/PROGRAMISTA.md`, AGENT.md, `vibe.md`.
## 1.7.10
### Poprawki
- White-label: branding czyta Site Settings przez `payload` przekazany przez Payload
(bez `import('@payload-config')`, którego Next nie bundlował); nazwa
zlokalizowana wg języka panelu.
## 1.7.9
### Nowe
- `<Analytics defer>` — tagi ładują się przy pierwszej interakcji albo po
`deferTimeoutMs` (domyślnie 3500 ms) od `load`; Consent Mode bez zmian.
- Eksport loaderów `loadMetaPixel`, `loadClarity`, `loadLinkedIn`, `loadTikTok`.
## 1.7.8
### Nowe
- **Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel** w Site
Integrations — ładowane dopiero po zgodzie na właściwą kategorię.
- Strona 404 z panelu (Site Settings → System Pages, `resolveNotFoundPage`).
### Wymaga zmian w projekcie
- `<Analytics>` musi być wewnątrz `<ConsentProvider>`.
## 1.7.7
### Bezpieczeństwo
- `/api/health` i MCP nie zwracają treści błędów (host bazy, schemat) — tylko
ogólny komunikat; szczegóły w logu serwera.
## 1.7.6
### Poprawki
- **noindex:** pole `buildNoindexField` jest top-level (`doc.noindex`) — wcześniejszy
zapis do `meta.noindex` był wycinany przez plugin-seo, więc strony noindex
trafiały do sitemapy. Sitemap, llms.txt, wyszukiwarka i metadata czytają `noindex`.
## 1.7.4
### Nowe
- 2FA: `twoFactor.plugin` — wstrzyknięcie `payloadTotp` zamiast dynamicznego importu.
- White-label: kredyt „Technology supported by Intecion.com” pod nawigacją i na
ekranie logowania; większe logo na logowaniu.
+5 -2
View File
@@ -15,7 +15,8 @@ Szczegóły API — jeden plik na moduł:
| Widget dostępności (opcjonalny) | [accessibility.md](./accessibility.md) |
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Zgoda cookies, baner | [consent.md](./consent.md) |
| Zgoda cookies, baner, okno ustawień (w pasku / modal / duże ze szczegółami ciasteczek) | [consent.md](./consent.md) |
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
| Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) |
@@ -27,10 +28,12 @@ Szczegóły API — jeden plik na moduł:
| Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
| Helpery Payload | [payload-helpers.md](./payload-helpers.md) |
| Rich text | [richtext.md](./richtext.md) |
| Rich text, spis treści | [richtext.md](./richtext.md) |
| Nagłówki, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Statystyki w panelu (bez cookies; historia odwiedzającego za zgodą) | [stats.md](./stats.md) |
| Auto-slug | [slug.md](./slug.md) |
| Motyw jasny / ciemny, przełącznik | [theme.md](./theme.md) |
| Media, R2 | [storage.md](./storage.md) |
| Turnstile | [turnstile.md](./turnstile.md) |
| White-label panelu | [white-label.md](./white-label.md) |
+150 -71
View File
@@ -52,21 +52,21 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| # | Obszar | Co musi być (plik) | API pluginu | Kontrola |
|---|---|---|---|---|
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` z ISR + `generateStaticParams`, `not-found.tsx` | `createProxy`, `createContentHelpers`, `resolveRoute`, `resolveRedirect` | A, S |
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, { load })` + `notFoundView.ts` (`renderNotFoundView`) | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` (wszystkie z `force-dynamic` poza robots) | `sitemapRoute`, `robots`, `createManifestHandler` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<JsonLdGraph>` z `WebSite` + `Organization` (`sameAs: sameAsUrls(settings)`) lub `LocalBusiness` (`type`, godziny tekstem z panelu → `formatOpeningHours`) + nawigacja `buildNavigationJsonLd(header)`; strona: `<JsonLdGraph schemas={await getPageJsonLd(locale, slug, { faq })} />` (WebPage/BlogPosting, okruszki, FAQ) | `build*JsonLd`, `getPageJsonLd`, `JsonLdGraph` (`/rsc`) | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` i `src/app/llms-full.txt/route.ts` (`full: true`); pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w trasach AI | `createLlmsTxtRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export const { GET } = createMarkdownRoute({…})`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `createMarkdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`) | `createMcpRoute` | A, S |
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `createIndexNowKeyRoute` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S |
| 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (jednojęzyczna: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S |
| 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S |
| 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
| 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); jeden `FormRenderer`; `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `createSubmitAction`, `useForm`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<TurnstileProvider siteKey={…}>` w `[locale]/layout.tsx`, `siteKey` z `getTurnstileConfig(payload)`; widget w `FormRenderer` (`useTurnstile`); klucze w Site Integrations | `getTurnstileConfig`, `TurnstileProvider`, `useTurnstile` | A, P |
| 12 | Zgoda + analityka | `ConsentProvider` (`logEndpoint` przy `consentLog: true`), `CookieBanner equalChoice`, `CookieButton`, `Analytics` w layoutcie; ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
| 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); blok z `<RenderForm>` + `formClasses.ts` (wygląd, raz); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` w `[locale]/layout.tsx` (wpina `TurnstileProvider` z kluczem z panelu); widget renderuje `RenderForm`; klucze w Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); tryb okna ustawień (`settings`: `inline` / `modal` / `detailed`) wg designu, brief milczy → `detailed`, decyzja do „Ustaleń projektu”; ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) — zasila `<CookieTable>` na stronie polityki **i** listy w oknie `detailed`; Cookie Settings → Detail labels w każdym języku | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A |
| 14 | Operacje | `src/app/api/health/route.ts`; `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `createHealthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę | `getSystemPagePath`, `getNotFoundPage` | P |
| 14 | Operacje | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Zero hardkodów** | każdy tekst, link, obraz, plik, dane firmy z panelu; domeny i klucze z `.env` (§2) | — | A, P |
| 17 | **Treść** | jedno h1, odpowiedź na początku sekcji, fakty, linki wewnętrzne, FAQ z prawdziwych pytań, `aiSummary`, sameAs, spójne dane firmy (§0c) | — | S, P |
| 18 | **Skalowanie** | `fluid.css` / `fluid-wide.css`, hero na `--ipal-hero-min-h`, lista ekranów §6.11a (w tym 1366×768) | — | A, przeglądarka |
@@ -83,12 +83,14 @@ Nie warunkujesz providera ani widgetu w kodzie — wpinasz zawsze.
| Zamiast pluginu | Dlaczego nie | Użyj |
|---|---|---|
| własny formularz z polami w JSX, `react-hook-form`, `formik` | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO | builder w panelu + `FormRenderer` + `submitForm` |
| własny formularz z polami w JSX, `react-hook-form`, `formik`, własny renderer formularzy | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO; kopia silnika przekazuje adresy z zakładki Emails do HTML | builder w panelu + `<RenderForm>` (wygląd: `formClasses`, nietypowe: `useBuilderForm`) |
| własna trasa `api/contact` / `api/send` / `api/form`, `nodemailer` / `resend` / `@sendgrid` w projekcie | omija walidację i bramki `submitForm`, drugi transport maili | server action `sendForm` → `submitForm`, maile z Forms → Emails przez `mailAdapter()` |
| reCAPTCHA, hCaptcha, własna captcha | drugi mechanizm, brak statusu w panelu | Turnstile z pluginu |
| ręczny `<script type="application/ld+json">` | brak escapowania, rozjazd z panelem | `JsonLdGraph` |
| własny `sitemap.ts` / tekstowy `robots.txt` w `public/` | bez hreflang, noindex i stron systemowych | `sitemapRoute`, `robots` z `lib/content` |
| własny `llms.txt` w `public/` | statyczny, starzeje się | `createLlmsTxtRoute` |
| własna funkcja linku (`resolveHref`, `getHref`…): slug strony głównej w kodzie (`=== 'home'`), `` `/${slug}` `` | brak prefiksu języka, strona główna zależy od Site Settings, `javascript:` z panelu w `href`, martwy link prowadzi na `/` | `resolveLink(link, locale)` / `resolveNav` z `lib/content` (pole: `buildLinkField`) |
| pola `page` + `url` + `label` w globalach, `prefooterButtonUrl`, `ctaLabel`; styl po treści (`label === 'Tesla'`); etykiety linków prawnych w kodzie | redaktor nie wybierze pliku / nowej karty / stylu; zmiana nazwy psuje wygląd; tekst PL w wersji EN | `buildLinkField` / `buildLinksField` z `appearances`, `resolveNav`, `getSystemLinks` |
| `@aws-sdk/client-s3` / własny upload do bucketa | omija hooki mediów i URL z `R2_PUBLIC_URL` | `buildR2Storage` |
### Świadomy wyjątek (tylko z decyzji klienta)
@@ -136,6 +138,8 @@ panelu (seed, faza 6 w ipal-site), stosujesz poniższe — nie wymyślając fakt
### Meta w zakładce SEO
Tytuł ≤ 60 znaków, unikalny, fraza na początku; opis ≤ 155 znaków, z konkretem i zachętą;
obraz udostępniania (1200×630) na stronach z ofertą — reszta dziedziczy domyślny z Site Settings.
Opis **unikalny na każdej stronie** — pusty uzupełnia się z treści przy zapisie, ale napisany
ręcznie jest lepszy. Ten sam opis na wielu stronach Google ignoruje.
### noindex — kiedy TAK, kiedy NIE
| Strona | noindex? |
@@ -281,23 +285,24 @@ src/
(frontend)/
styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
layout.tsx # bez <head>; JsonLdGraph, TurnstileProvider, ConsentProvider + Analytics
actions.ts # sendForm → submitForm (jedyna droga wysyłki formularzy)
not-found.tsx # 404 z panelu (getNotFoundPage)
[[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks
layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy)
not-found.tsx # createNotFoundPage(content, { load: loadNotFoundView }) — 404 z panelu
notFoundView.ts # 'use server' → renderNotFoundView(content, { blocks }, locale)
[[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate
(payload)/ # panel (generowany)
manifest.ts # createManifestHandler + force-dynamic
sitemap.xml/route.ts # sitemapRoute z lib/content + force-dynamic (wygląd z pluginu)
robots.ts # z lib/content (boty AI wpuszczone)
llms.txt/route.ts # createLlmsTxtRoute (GEO)
llms-full.txt/route.ts # createLlmsTxtRoute({ full: true }) (GEO)
md/[locale]/[[...slug]]/route.ts # createMarkdownRenderer — strona jako Markdown (GEO)
api/mcp/route.ts # createMcpRoute — publiczny serwer MCP (GEO)
api/health/route.ts # createHealthRoute
manifest.ts # export { manifest as default } from lib/content + force-dynamic
sitemap.xml/route.ts # export { sitemapRoute as GET } + force-dynamic (wygląd z pluginu)
robots.ts # export { robots as default } (boty AI wpuszczone)
llms.txt/route.ts # export { llmsRoute as GET } (GEO)
llms-full.txt/route.ts # export { llmsFullRoute as GET } (GEO)
md/[locale]/[[...slug]]/route.ts # export { markdownRoute as GET } — strona jako Markdown (GEO)
api/mcp/route.ts # export { mcpGET as GET, mcpPOST as POST } — publiczny MCP (GEO)
api/health/route.ts # export { healthRoute as GET }
indexnow-key.txt/route.ts # export { indexNowKeyRoute as GET }
instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env'
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/
forms/FormRenderer.tsx # jedyny renderer formularzy z panelu (ipal-form)
forms/formClasses.ts # JEDYNE miejsce wyglądu formularzy (RenderForm classNames)
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
layout/ # Header, Footer, MobileNav (§6.8)
icons/ # names.ts + Icon.tsx (§6.10)
@@ -305,13 +310,17 @@ src/
blocks/registry.ts # blockType → komponent
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/navigation.ts # resolveNav → dane dla menu
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada, trasy, linki, nawigacja
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # NIE middleware.ts
```
Trasy w `app/` to **re-eksporty** z `lib/content` — konfiguracja (domena, `summaryField`,
nazwa MCP) jest raz, w `createContentHelpers`. Pola sekcji (`buildSectionHeaderField`,
`buildSectionSettingsField`), linki (`resolveLink`) i menu (`resolveNav`) są w pluginie —
nie twórz `src/fields/sectionHeader.ts` ani `lib/navigation.ts`.
| Element | Konwencja | Przykład |
|---|---|---|
| Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` |
@@ -322,7 +331,7 @@ src/
| Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` |
Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
`lib/locales.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`.
`lib/locales.ts`, `lib/navigation.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`, `resolveNav`.
---
@@ -344,7 +353,8 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
statycznych — w blokach, komponentach, layoucie `[locale]` ani w
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
wersja na każdy język + `<LocaleView>` (pages.md).
`createNotFoundPage(content, { load })` — język z adresu, treść z server action dopiero przy 404
(wariant `{ blocks }` wkłada 404 w każdym języku do danych RSC KAŻDEJ strony — pages.md).
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
`manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
@@ -433,8 +443,8 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
### 6.1 Trzy warstwy
```
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
+ src/fields/ projektu (sectionHeader, sectionSettings)
WARSTWA 1 — wspólne pola: z pluginu (buildLinkField, buildLinksField,
buildSectionHeaderField, buildSectionSettingsField)
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
```
@@ -460,10 +470,11 @@ pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink
pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz
przed wgraniem — hook tylko łapie wpadki i pyta o zgodę.
**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.
**Nagłówek i ustawienia sekcji — z pluginu** ([blocks.md](../blocks.md)):
- `buildSectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `buildSectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`
(tła projektu: `buildSectionSettingsField({ backgrounds: [{ label, value }] })`, dodatkowe pola: `fields`).
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
Etykiety pól po angielsku (panel jest EN).
### 6.3 Warstwa 2 — prymitywy UI
@@ -472,16 +483,16 @@ Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma
| 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 |
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLink(link, locale)` z `lib/content` (href, `internal`, `targetProps`, `appearance`) + klasy z `Button` | `<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 = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props
```
`createPageRoute` podaje każdemu blokowi `locale` + to, co zwróci `blockProps`
(np. `{ formTexts, sendForm }`). Własna strona: `enhanceProps={() => ({ locale })}`.
Turnstile i zgoda są w `<SiteProviders>` w layoucie, nie w propsach.
### 6.4 Warstwa 3 — sekcja = kompozycja
@@ -528,11 +539,11 @@ Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/c
| 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` |
| Nagłówek sekcji | `header` (`buildSectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
| Tekst elementu | `heading` + `text` | `title`/`desc`/`description` naprzemiennie |
| Tekst sformatowany | `content` (richText) | `body`, `html`, `richText` |
| Lista elementów | `items` | `cards`, `features`, `list`, `boxes` |
| Anchor / tło | `settings` (`sectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
| Anchor / tło | `settings` (`buildSectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
| Zgoda RODO w formularzu | `consent` (checkbox) | — |
Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
@@ -584,12 +595,12 @@ pustych pól, bez zgadywania, bez numerowanych slotów. Schemat projektujesz dla
{ name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } },
// DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …”
sectionHeaderField(), // Eyebrow / Heading / Intro
buildSectionHeaderField(), // Eyebrow / Heading / Intro
{ name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6,
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') },
fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] },
buildLinksField(), // „+ Add Button”
sectionSettingsField(), // sidebar: anchor, background
buildSectionSettingsField(), // sidebar: anchor, background
```
**Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie →
@@ -634,16 +645,21 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.8 Header i Footer (globale nawigacji)
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Kod (globale, `Header`, `Footer`, `MobileNav`; `resolveNav` z pluginu): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Skill: **ipal-nav**.
- 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.
- **Treść stopki w `<NoSnippet>`** (`/rsc`, wewnątrz `<footer>`) — inaczej Google pokazuje adres
ze stopki jako opis każdej podstrony. To samo dla paska kontaktowego i CTA powtarzanego na
każdej stronie. Nigdy na `<main>`. Szczegóły: seo.md → „Opisy w Google”.
- **Linki prawne w stopce** z ról System Pages: `await getSystemLinks(locale)` (href + tytuł strony), nie ręcznie i bez etykiet w kodzie.
- Wyróżnienie pozycji menu / wariant przycisku = `appearance` z panelu (`buildLinkField({ appearances: [...] })`, dowolne nazwy), nigdy warunek na treści (`label === '…'`).
- Linki rozwiązuj **na serwerze**: `await resolveNav(header.navItems, locale)` z `lib/content`
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte); do
komponentu klienckiego (MobileNav) idą tylko te 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.
@@ -748,36 +764,99 @@ Kontrole: `ipal-audit` (img/video poza Media, wiele `priority`, `h-screen`, sta
## 7. WZORCE PLUGINU — UŻYWAJ, NIE PISZ OD NOWA
Katalog: **potrzeba → import**. Zanim napiszesz helper, hook, komponent logiki albo trasę —
znajdź ją tutaj. Wejścia: `@intecion/ipal-kit` (serwer/config), `/client` (`'use client'`),
`/rsc` (komponenty serwerowe), `/server` (server actions), `/admin` (panel), `/env`
(`instrumentation.ts`). Plugin daje **logikę i szkielet**; wygląd zostaje w projekcie
(klasy, `classNames`, własny markup na hooku). Nie ma czegoś, co powtórzy się w innym
projekcie → **ipal-plugin-gap**, nie kopia.
**Strona i dane** (`lib/content.ts` = `createContentHelpers`, PROGRAMISTA §2.7)
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md |
| Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md |
| Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { load })` + server action `renderNotFoundView(content, { blocks, fallback }, locale)` (`/rsc`) | pages.md |
| Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md |
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.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 |
| Formularz | builder w panelu + `FormRenderer` + akcja `sendForm` → `submitForm`; logika `useForm`; IP: `clientIp(await headers())` | forms.md |
| Turnstile | `TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}` w layoutcie + `useTurnstile()` — przy obu kluczach token jest wymagany | turnstile.md |
| Slug | `buildSlugField({ from: 'title' })` | slug.md |
| noindex | `buildNoindexField()` | seo.md |
| Ścieżki językowe | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher` | i18n.md |
| Strony systemowe, 404 | `getSystemPagePath`, `getNotFoundPage` | pages.md |
| Routing, archiwa | `resolveRoute`, `getEntries`, `resolveRedirect` | content.md |
| ISR po zapisie | `buildRevalidateHook` (wstrzyknięty `revalidatePath`) | hooks.md |
| 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 | `generatePageMetadata` (z `createContentHelpers`), `sitemapRoute`, `build*JsonLd` + `JsonLdGraph` | seo.md |
| GEO (AI) | `createLlmsTxtRoute` (+ `full: true`), `createMarkdownRenderer` + `markdownResponse`, `markdownAlternate: true`, `createProxy({ markdown: true })`, `createMcpRoute`, `buildSummaryField` | seo.md, content.md, mcp.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(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField`, `MediaPreconnect` | storage.md |
| Email | `email: mailAdapter()` | email.md |
| Walidacja env | `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` | env.md |
| Rich text / Lexical → Markdown | `RenderRichText` (`/rsc`, styl przez `converters`), `lexicalToMarkdown` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | i18n.md |
**Pola i panel**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md |
| Link do kategorii / produktu / wpisu | `buildLinkField({ relationTo: ['pages', 'categories'] })` — adres z archiwum | links.md |
| Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md |
| Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md |
| Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md |
| Strony systemowe i ich ochrona | `getSystemPagePath`, `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | pages.md, hooks.md |
| ISR po zapisie, stary slug → 308, obrazy między językami | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| Role i dostęp | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`) | access.md |
| Dane z globali | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Linki i nawigacja**
| Potrzeba | Użyj | Doc |
|---|---|---|
| href + nowa karta + rel + internal dla linku z panelu | `resolveLink(link, locale)` (`lib/content`) / `resolveLink(link, opts)` | links.md |
| Menu z globala (dowolna głębokość, martwe linki pominięte) | `resolveNav(items, locale)` | links.md |
| Linki prawne w stopce (href + tytuł strony) | `getSystemLinks(locale)` / `resolveSystemLinks` | links.md |
| Wyróżniona pozycja, wariant przycisku | `buildLinkField({ appearances: [...] })` — nazwy projektu | links.md |
| Ścieżki językowe, przełącznik, hreflang | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher`, `buildLocalizedPath` | i18n.md |
| Bezpieczny URL (bez `javascript:`) | `safeHref` | links.md |
**Formularze**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Formularz z panelu w bloku (kroki, radio, listy, daty) | `<RenderForm form action locale texts classNames>` (`/rsc`) | forms.md |
| Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md |
| Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| Pole wypełniane przez stronę (wariant produktu, kategoria) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md |
| Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.md |
| Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md |
| Antyspam / limit / IP | honeypot w `BuilderForm`, Turnstile z `SiteProviders`, `clientIp`, `setRateLimitStore` | forms.md, turnstile.md |
| Zdarzenie GTM po wysłaniu | `buildFormAnalyticsFields` (panel) — `RenderForm` wysyła je sam | forms.md |
| Formularz spoza buildera (np. filtry) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
**SEO i GEO** (trasy = re-eksport z `lib/content`)
| Potrzeba | Użyj | Doc |
|---|---|---|
| Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md |
| sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md |
| JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `<JsonLdGraph>` | seo.md |
| JSON-LD produktu / kategorii (wpis, który nie jest artykułem) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md |
| llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md |
| IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Wyszukiwarka | `createSearchRoute` | content.md |
**Media, wygląd, szybkość**
| Potrzeba | Użyj | Doc |
|---|---|---|
| R2, nazwy plików, optymalizacja, podgląd | `buildR2Storage`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` | storage.md |
| Obraz / wideo w `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
| YouTube bez ciasteczek przed kliknięciem | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
| Płynna typografia i odstępy | `fluid.css` / `fluid-wide.css` (zmienne `--ipal-*`) | PROGRAMISTA §2.5 |
**Zgoda, analityka, operacje**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Baner, ustawienia, przycisk cookies | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
| Okno ustawień: w pasku / małe / duże ze szczegółami ciasteczek | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — nie buduj własnego okna ani listy ciasteczek | consent.md → „Duże okno ze szczegółami” |
| Skrypt zależny od zgody | `ConsentScript` | consent.md |
| Tabela ciasteczek na polityce | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | ID w panelu — `SiteProviders` ładuje `Analytics` (`analytics={{ defer: true }}`) | analytics.md |
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
| Walidacja env, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md |
| 2FA, white-label, nagłówki | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md |
| Rate limit (formularze, MCP, wyszukiwarka) | wbudowany; IP z `IPAL_IP_HEADER`; kilka instancji → `setRateLimitStore` | forms.md |
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
formularzach (enforcement server-side), dane administratora w globalu, tabela
ciasteczek z panelu (`<CookieTable>`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
ciasteczek z panelu (`<CookieTable>` i okno `settings="detailed"`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
wymaga (accessibility.md).
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
+67 -19
View File
@@ -41,7 +41,8 @@ report() {
g() { grep -rnE "$@" 2>/dev/null || true; }
# drop matches that sit inside a // or /* comment (keeps http:// URLs)
nc() { grep -vE "(^|[^:])//.*$1|/\*.*$1" || true; }
# (also a whole-line comment right after grep's "file:line:" prefix)
nc() { grep -vE "^[^:]+:[0-9]+:[[:space:]]*(//|/?\*)|(^|[^:])//.*$1|/\*.*$1" || true; }
dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; }
BLOCKS=$(dirs src/blocks)
@@ -52,7 +53,7 @@ echo "ipal-audit — $(pwd)"
# --- Skill templates must not be compiled as project code ---
if [ -d .agents ] && [ -f tsconfig.json ]; then
report ERROR "tsconfig.json does not exclude .agents" "skill templates (.ts/.tsx) break tsc / next build — \"exclude\": [\"node_modules\", \".agents\"]" \
"$(grep -qE '"exclude"[^]]*\.agents' tsconfig.json || echo tsconfig.json)"
"$(tr -d '\n' < tsconfig.json | grep -qE '"exclude"[^]]*\.agents' || echo tsconfig.json)"
fi
# --- Sitemap: one route, look from the plugin (seo.md) ---
@@ -189,6 +190,31 @@ report WARNING "files that usually duplicate the plugin" "§3 plugin has resolve
"$(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)"
# Hand-rolled link resolution under another name (resolveHref, getHref…): the plugin knows the
# homepage from Site Settings, adds the locale prefix, drops unsafe URLs and dead links.
FRONT=$(dirs src/app src/blocks src/components src/lib src/globals src/collections)
if [ -n "$FRONT" ]; then
report ERROR "hardcoded homepage slug" "links.md — the homepage comes from Site Settings: resolveLink(link, locale) / getHomeSlug(locale), never a slug name in code" \
"$(g "(===|!==|==|!=) *['\"](home|homepage|strona-glowna|glowna|start|index)['\"]|['\"](home|homepage|strona-glowna|glowna|start|index)['\"] *(===|!==|==|!=)" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | grep -vE "[Tt]ype *[!=]==? *['\"]home|['\"]home['\"] *[!=]==? *[A-Za-z_.]*[Tt]ype" | nc '=')"
report ERROR "URL built from a slug by hand" "links.md — resolveLink / resolveNav (lib/content) or buildLocalizedPath: locale prefix, homepage, unsafe and dead links" \
"$(g '`/\$\{[^}]*[Ss]lug|`\$\{[A-Za-z_.]*\}/\$\{[^}]*[Ss]lug|['"'"'"]/['"'"'"] *\+ *[A-Za-z_.?]*[Ss]lug' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
# `${prefix}/kontakt`, `/${locale}/kontakt` — a page path typed into the code (fallback links)
report ERROR "page path hardcoded in a link" "links.md — a missing link renders nothing; never a fallback to a slug typed in code" \
"$(g '`\$\{[A-Za-z_.]*\}/[a-z][a-z0-9-]*`|`/\$\{locale\}/[a-z][a-z0-9-]*`' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '`')"
fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
report ERROR "link/button fields in globals" "§6.5 Header/Footer links and buttons = buildLinkField / buildLinksField (page, URL or file + label + style), never ctaLabel/buttonUrl/…Url" \
"$(g "name: *'[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df)[a-zA-Z]*'" $GLOBALS --include=*.ts)"
report WARNING "page relationship in a global" "links.md — a link to a page is buildLinkField (it also handles URL, file, new tab, style); then resolveNav / resolveLink" \
"$(g "relationTo: *'pages'" $GLOBALS --include=*.ts)"
fi
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
"$(g 'node\.type *===' src --include=*.tsx | nc 'node')"
HTML=$(node "$(dirname "$0")/html-check.mjs" src)
@@ -216,31 +242,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 (one language: src/app/md/[[...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
@@ -251,6 +277,15 @@ if [ -n "$CFG" ]; then
need ERROR '' "forms in ipalKit" "$CFG → ipalKit({ forms: {…} }) — forms are built in the panel" 'forms *:' "$CFG"
need ERROR '' "mailAdapter" "$CFG → email: mailAdapter() — form e-mails go through the panel transport" 'mailAdapter\(' "$CFG"
need ERROR r2 "R2 storage" "$CFG → buildR2Storage(['media'], { s3Storage }) — always wired, local disk only without R2_* env" 'buildR2Storage' "$CFG"
# pnpm dev / generate:importmap with ipal-kit < 1.12.2 and no R2_* env dropped the storage-s3
# client handler → blank admin in production (where R2 is on)
if grep -q 'buildR2Storage' "$CFG" 2>/dev/null; then
for IM in src/app/\(payload\)/*/importMap.js; do
[ -f "$IM" ] || continue
report ERROR "import map without the R2 upload handler" "storage.md — pnpm payload generate:importmap (ipal-kit ≥ 1.12.2 writes it with or without R2_* env); without it the production admin renders blank" \
"$(grep -q 'S3ClientUploadHandler' "$IM" || echo "$IM")"
done
fi
need ERROR r2 "@payloadcms/storage-s3" "pnpm add @payloadcms/storage-s3 (same version as payload)" '"@payloadcms/storage-s3"' package.json
need ERROR twofactor "2FA" "$CFG → twoFactor: { issuer, plugin: payloadTotp }" 'payloadTotp' "$CFG"
report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \
@@ -271,9 +306,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
@@ -285,7 +332,8 @@ if [ "$QUICK" -eq 0 ]; then
echo "== pnpm build =="
BUILD_LOG=$(mktemp)
if pnpm -s build >"$BUILD_LOG" 2>&1; then
DYN=$(grep -E '^[│├└ ]*ƒ .*\[locale\]' "$BUILD_LOG" || true)
# Only page routes under /[locale]: route handlers (/md/[locale]/…, sitemap, llms) are force-dynamic by design.
DYN=$(grep -E '^[│├└ ]*ƒ /\[locale\]' "$BUILD_LOG" || true)
report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN"
else
ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /'
@@ -21,6 +21,9 @@ const WORD = /\p{L}{2,}/u
// Text right after a closing/self-closing tag may be the JS that follows the JSX
// expression (`<X /> : null`, `</div>) }`, `</p>\n const id = …`) — not visible text.
const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/
// JSX elements as values in an object literal: `narrow: <A />,\n wide: <B />` leaves
// ", wide:" between the two elements — a property key, not visible text.
const OBJECT_KEY = /^\s*,\s*(?:[A-Za-z_$][\w$]*|'[^']*'|"[^"]*")\s*:\s*$/
const files = []
const walk = (p) => {
@@ -44,7 +47,7 @@ for (const file of files) {
const src = stripComments(readFileSync(file, 'utf8'))
for (const m of src.matchAll(OPEN_OR_CLOSE)) {
const text = m[1].replace(/\s+/g, ' ').trim()
if (!text || !WORD.test(text) || JS_CODE.test(text)) continue
if (!text || !WORD.test(text) || JS_CODE.test(text) || OBJECT_KEY.test(text)) continue
if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue
console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`)
}
@@ -22,7 +22,8 @@ for (const file of files) {
const src = strip(readFileSync(file, 'utf8'))
// numbered slots: cta1Label, feature2Title, image3, phone2 → array with "+ Add …"
for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+[a-zA-Z0-9]*)['"]/g)) {
// digits at the end or before a new word (cta1Label) — not numeronyms like a11y, i18n, l10n
for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+(?:[A-Z][a-zA-Z0-9]*)?)['"]/g)) {
if (/^(h[1-6]|x[0-9]|[a-z]?2fa)$/i.test(m[1])) continue
out('ERROR', 'numbered fields → one array field with labels {singular, plural} ("+ Add …")', file, src, m.index, m[1])
}
@@ -30,7 +31,7 @@ for (const file of files) {
// panel text must be English and short
for (const m of src.matchAll(/\b(label|description|singular|plural|placeholder)\s*:\s*(['"`])((?:(?!\2).)*)\2/g)) {
const text = m[3]
if (POLISH.test(text)) out('WARNING', 'panel is English — labels/descriptions in English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`)
if (POLISH.test(text)) out('WARNING', 'panel text in Polish — admin labels/descriptions are English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`)
else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`)
}
+5 -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 — 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
@@ -20,7 +21,8 @@ buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała k
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`
powstaje typ `CmsLink` (bez stylu: `CmsLinkPlain`, bez etykiety: `CmsLinkNoLabel`; wszystkie
pasują do `CmsLink`; własna nazwa: `interfaceName`). Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
(domyślnie `'media'`), `required`.
@@ -29,53 +31,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 +51,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 +64,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 +180,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 +226,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 +243,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
@@ -36,7 +36,7 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
renderowany albo starsza wersja ipal-kit bez atrybutów `data-ipal` na przyciskach → **ipal-upgrade**.
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
`CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7.
`CookieBanner` z pluginu w każdym trybie `settings` (`inline`, `modal`, `detailed`). Własny baner w projekcie to naruszenie AGENT.md §7.
## Lista ciasteczek do polityki cookies (cookie-scan)
@@ -55,7 +55,10 @@ Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem s
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
```
Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek,
których skan nie widział — to robi redaktor w panelu.
których skan nie widział — to robi redaktor w panelu. Ta sama lista zasila okno
`<CookieBanner settings="detailed">` (rozwijana lista pod każdą kategorią) — po imporcie otwórz
„Ustawienia” w banerze i sprawdź, że każda kategoria pokazuje swoje ciasteczka, a podpisy
(Cookie Settings → Detail labels) są w danym języku.
3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**:
```tsx
import { getCookieTable, getConsentTexts } from '@intecion/ipal-kit'
@@ -1,6 +1,7 @@
/**
* Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the
* cookie policy page (<CookieTable>) lists what the site really sets.
* cookie policy page (<CookieTable>) and the detailed consent window
* (<CookieBanner settings="detailed">) list what the site really sets.
*
* LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
* # second language: scan again with --lang en, then import with LOCALE=en
+52 -34
View File
@@ -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,63 @@ 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`.
**Pole wypełniane przez stronę** (wybrany wariant produktu, kategoria, oferta): w panelu zwykłe pole tekstowe
(np. `subject`), w kodzie `RenderForm values={{ subject }}`; wartość zmieniana w przeglądarce →
`prepareBuilderForm` (serwer) + `<BuilderForm values>` (klient). Nigdy kopia `publicForm` w projekcie (forms.md).
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 +129,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 +138,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 -1
View File
@@ -53,7 +53,7 @@ Uzupełnij w tej kolejności (panel albo skrypt Local API z `locale: 'de'`):
| Homepage/404/polityka | System Pages (relacje wspólne) + ich slug w `de` | `/de` → 404, link polityki pusty |
| Header / Footer — etykiety linków | globale nawigacji | puste pozycje menu |
| Site Settings — nazwa, opis, OG | Site Settings | tytuł/OG z fallbacku |
| Cookie Settings — wszystkie teksty + `privacyLinkLabel` | Cookie Settings | baner w innym języku (RODO: zgoda musi być zrozumiała) |
| Cookie Settings — wszystkie teksty + `privacyLinkLabel`, Detail labels, Cookies (`purpose`, `duration`) | Cookie Settings | baner / okno `detailed` w innym języku (RODO: zgoda musi być zrozumiała); skan + import z `--lang <kod>` (ipal-consent-check) |
| Notifications — `form.*` | Notifications | komunikaty formularza z angielskiego fallbacku |
| Forms — etykiety pól, potwierdzenie, Emails | Forms (każdy formularz) | formularz w złym języku |
| SEO tab — meta title/description | każda strona | duplikaty/braki w seo-check |
+6 -5
View File
@@ -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,11 +19,12 @@ 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).
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
(`'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: `getSystemLinks(locale)` (href + 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.
7. Podepnij w `src/app/(frontend)/[locale]/layout.tsx` (pobranie globali przez
@@ -78,57 +78,26 @@ export const Footer: GlobalConfig = {
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
- **Linki prawne w stopce** (polityka, cookies, regulamin): `await getSystemLinks(locale)` z `lib/content`
— href i etykieta (tytuł strony) z System Pages; nie dodawaj ich ręcznie do `columns`, nie wpisuj etykiet w kod.
- Wyróżniona pozycja menu / przycisk w innym kolorze = styl w panelu:
`buildLinkField({ appearances: ['default', { label: 'Highlighted', value: 'highlight' }] })` → klasa w projekcie.
- **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).
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 +110,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 +127,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)
@@ -186,3 +153,14 @@ export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: s
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.
Komponent `Footer` — treść w `NoSnippet` (inaczej Google pokazuje adres ze stopki jako
opis każdej podstrony; seo.md → „Opisy w Google”):
```tsx
import { NoSnippet } from '@intecion/ipal-kit/rsc'
<footer className="…">
<NoSnippet className="…">{/* dane firmy, linki, linki prawne */}</NoSnippet>
</footer>
```
+2 -2
View File
@@ -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) |
@@ -98,7 +98,8 @@ for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
const multiLocale = hasAlternates || byLocale.size > 1
const urlSet = new Set(urls.map(norm))
const titles = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [] }
const descriptions = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [], footerSnippet: [] }
const checkedPaths = []
for (const url of sample) {
@@ -120,7 +121,9 @@ for (const url of sample) {
if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`)
titles.set(title, [...(titles.get(title) ?? []), url])
}
if (!/<meta[^>]+name="description"[^>]+content="[^"]+"/i.test(head)) issues.desc.push(url)
const desc = tags(head, /<meta[^>]+name="description"[^>]*>/gi).map((t) => attr(t, 'content'))[0]?.trim()
if (!desc) issues.desc.push(url)
else descriptions.set(desc, [...(descriptions.get(desc) ?? []), url])
const canonTag = tags(head, /<link[^>]+rel="canonical"[^>]*>/gi)[0]
const canon = canonTag && attr(canonTag, 'href')
@@ -161,6 +164,9 @@ for (const url of sample) {
try { const u = new URL(href, url); return u.host === own && norm(u.pathname) !== norm(new URL(url).pathname) } catch { return false }
})
if (internal.length === 0) issues.noLinks.push(url)
// Repeated footer text (address, hours) is what Google quotes for brand searches
const footer = main.match(/<footer\b[\s\S]*<\/footer>/i)?.[0]
if (footer && !/data-nosnippet/i.test(footer)) issues.footerSnippet.push(url)
if (multiLocale) {
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
@@ -174,6 +180,7 @@ for (const url of sample) {
}
const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`)
const dupDescs = [...descriptions.entries()].filter(([, us]) => us.length > 1).map(([d, us]) => `"${d.slice(0, 60)}…" × ${us.length}`)
if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status)
if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead)
if (issues.body.length) report('ERROR', 'metadata rendered in <body>', 'htmlLimitedBots, no explicit <head>, ISR + generateStaticParams (AGENT.md §4)', issues.body)
@@ -186,6 +193,8 @@ if (issues.xdefault.length) report('WARNING', 'no x-default hreflang', 'buildHre
if (issues.reciprocal.length) report('WARNING', 'hreflang alternates not in the sitemap', 'translation missing/unpublished or noindex in that locale', issues.reciprocal.slice(0, 15))
if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO tab in the panel (or site description fallback)', issues.desc)
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
if (dupDescs.length) report('WARNING', 'duplicate meta descriptions (Google ignores them)', 'own description per page in the SEO tab — empty ones auto-fill from content on save', dupDescs)
if (issues.footerSnippet.length) report('WARNING', 'footer without data-nosnippet (Google quotes the address as the snippet)', 'wrap footer contents in <NoSnippet> (seo.md → Opisy w Google)', issues.footerSnippet.slice(0, 3))
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
if (issues.xRobots.length) report('ERROR', 'X-Robots-Tag: noindex on pages', 'IPAL_NOINDEX is set in this environment — remove it in production', issues.xRobots.slice(0, 3))
@@ -223,7 +232,7 @@ if (!skipped('markdown') && checkedPaths.length) {
const path = checkedPaths[0]
const md = await ok(`/md${path === '/' ? '' : path}`)
const type = md?.res.headers.get('content-type') ?? ''
if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts (content.md)')
if (!md || md.res.status !== 200 || !/markdown/i.test(type)) report('ERROR', `Markdown version /md${path} → ${md?.res.status ?? 'unreachable'} ${type}`, 'src/app/md/[locale]/[[...slug]]/route.ts; one language: src/app/md/[[...slug]]/route.ts (i18n.md)')
}
if (!skipped('mcp')) {
let mcpOk = false
+13 -11
View File
@@ -38,21 +38,23 @@ 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 settings="detailed" />}>`
(tryb okna ustawień `inline` / `modal` / `detailed` wg designu — consent.md),
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
`not-found.tsx`: `createNotFoundPage(content, { load: loadNotFoundView })` + `notFoundView.ts` z
`renderNotFoundView` (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.
na stronie polityki cookies; ta sama lista pokazuje się w oknie `settings="detailed"` (Detail labels w panelu).
10. **Nawigacja** — skill **ipal-nav**.
11. **Kontrola kompletu** — `pnpm generate:types`, `pnpm payload generate:importmap`,
**ipal-audit** (pełny) = 0 błędów, w tym sekcja „missing: …” (§0b); po
+2 -2
View File
@@ -68,8 +68,8 @@ formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md
Nie wymyślaj danych firmy, cen, opinii, liczb, certyfikatów, nazwisk.
2. `pnpm payload run scripts/seed-content.ts` → lista placeholderów trafia do raportu.
3. System Pages: Homepage, 404, polityka prywatności (strona istnieje; treść
polityki od klienta → placeholder). Cookie Settings, Notifications — teksty w
każdym języku.
polityki od klienta → placeholder). Cookie Settings (z Detail labels i listą Cookies
ze skanu), Notifications — teksty w każdym języku.
4. **ipal-locale-add → `locale-coverage`** = 0 braków (albo świadome w raporcie).
5. Obrazy: zostawiasz puste pola upload (redaktor dodaje) albo wgrywasz pliki z
briefu przez panel — przygotowane (WebP/JPG ≤ 1.5 MB, ≤ 2560 px).
+25
View File
@@ -30,6 +30,31 @@ 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).
**→ 1.11.0 (PROGRAMISTA §6, poz. 34–37):** usuń obejścia — kopię `publicForm` (→ `RenderForm values` /
`prepareBuilderForm`), ręczne `remotePatterns`/`dangerouslyAllowLocalIP` (→ `buildImagesConfig()`), warunkowe
`storage` w `ipalEnvRules`, własny graf JSON-LD produktów (→ `pageJsonLd.entries` + `buildProductJsonLd`),
własny RenderBlocks dla `h1` (→ `isFirst`). Linki do wpisów: `buildLinkField({ relationTo: [...] })` z migracją danych.
**→ 1.11.1 (PROGRAMISTA §6, poz. 38–45):** usuń obejścia (komentarze `WORKAROUND ipal-kit`) — warunek
`NEXT_RUNTIME` wokół `revalidatePath`, strażnik fokusu formularza, własny motyw (→ `ThemeScript`/`ThemeSwitcher`),
własny spis treści (→ `extractHeadings` + `TableOfContents` + `headingIds`), łapanie `notFound` dla przekierowania
(→ `onMissing: 'redirectHome'`), kolor tła tylko dla JPEG w `<Media>`, typowanie przez `ButtonAppearance` zamiast
`CmsLink['appearance']` (typy linków bez stylu to teraz `CmsLinkPlain`). Cookie Settings: `buttons.save` →
`buttons.savePreferences` — w `migrate:create` wybierz **rename** kolumny, żeby zachować teksty.
**→ 1.12.3 (PROGRAMISTA §6, poz. 46):** Postgres/SQLite: `migrate:create` (nowa grupa Cookie Settings →
`detailLabels`, same nowe kolumny — bez rename). Własne okno ustawień cookies albo lista ciasteczek dopisana do
banera → `<CookieBanner settings="detailed">` i usuń kopię. Przy `detailed`: Cookie Settings → Cookies wypełnione
(skan, **ipal-consent-check**) i Detail labels w każdym języku.
## 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.
+17
View File
@@ -74,6 +74,23 @@ const enhanceProps = ({ block, allBlocks }) => {
<RenderBlocks blocks={page.layout} components={registry} enhanceProps={enhanceProps} />
```
## Wspólne pola sekcji — `buildSectionHeaderField`, `buildSectionSettingsField`
```ts
import { buildLinksField, buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
fields: [
buildSectionHeaderField(), // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
…pola bloku…,
buildLinksField(),
buildSectionSettingsField(), // sidebar `settings`: anchor, background — typ SectionSettings
]
```
Wszystko do zmiany: `buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }], anchor: false,
fields: [{ name: 'spacing', … }] })`, `backgrounds: false` (bez wyboru tła), `buildSectionHeaderField({ name, fields,
interfaceName })`. Wartości tła mapuje na klasy `<Section>` projektu. Kształt danych taki jak dawne
`src/fields/sectionHeader.ts` / `sectionSettings.ts` z kod-sekcji.md — zamiana importu nie wymaga migracji.
## Komponent bloku
Każdy komponent dostaje dane bloku jako propsy (plus `_components`, plus to co
+91 -6
View File
@@ -2,8 +2,9 @@
Banner zgody na cookies (GDPR): 4 kategorie (necessary / functional /
analytics / marketing), zapis w cookie z wersjonowaniem, Google Consent Mode,
treść z globala CookieSettings. Domyślny wygląd w czystym Tailwind,
nadpisywalny.
treść z globala CookieSettings. Okno ustawień w trzech trybach do wyboru
(`settings`: w pasku, małe okno, duże okno ze szczegółami ciasteczek). Domyślny
wygląd w czystym Tailwind, nadpisywalny.
## Zależność
@@ -36,6 +37,14 @@ okazji aktualizacji.
## Front — Provider + banner
Zwykle jedną linią w layoutcie (PROGRAMISTA §2.8) — `SiteProviders` (`/rsc`) wpina provider,
baner, przycisk i `Analytics` w dobrej kolejności, z tekstami z `getSiteShell(locale).consent`:
```tsx
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent"
banner={<CookieBanner equalChoice classNames={…} />}>{children}</SiteProviders>
```
Ręcznie (własny układ) — to samo z pojedynczych części:
Provider owija aplikację, banner i button renderują się same. Import z
`@intecion/ipal-kit/client`:
@@ -160,15 +169,90 @@ zmienna po zmiennej. Na większe zmiany są `classNames`:
<CookieButton className="fixed bottom-6 right-6 ..." />
```
Sloty: `root`, `primaryButton`, `secondaryButton`. Podany className zastępuje
domyślny (nie dokleja się).
Podany className zastępuje domyślny (nie dokleja się). Każdy element ma swój slot (1.10.0):
| Slot | Element |
|---|---|
| `root`, `body`, `content` | pasek, wewnętrzna szerokość, rząd tekst + przyciski |
| `text`, `icon`, `eyebrow`, `title`, `message`, `link` | blok tekstu banera |
| `actions` | rząd przycisków banera |
| `primaryButton`, `secondaryButton` | dwa style przycisków (domyślne dla wszystkich) |
| `acceptButton`, `rejectButton`, `settingsButton`, `saveButton`, `backButton` | pojedyncze przyciski — puste → `primaryButton` / `secondaryButton` |
| `overlay`, `dialog`, `closeButton` | modal ustawień (`settings="modal"` / `"detailed"`) |
| `categoryCard`, `cookies`, `cookiesToggle`, `cookieList`, `cookie`, `cookieName`, `cookieMeta` | duże okno (`settings="detailed"`): karta kategorii, rozwijana lista ciasteczek, jedno ciasteczko, nazwa, siatka dostawca / cel / czas |
| `settingsTitle`, `settingsDescription`, `categories`, `category`, `categoryTitle`, `categoryDescription` | widok ustawień |
| `control`, `controlThumb`, `badge` | checkbox / przełącznik, kciuk przełącznika, znacznik „Zawsze aktywne” |
| `settingsActions` | rząd przycisków pod kategoriami |
### Układ: kolejność przycisków, modal, przełączniki (1.10.0)
```tsx
<CookieBanner
equalChoice
icon={false} // bez ikony ciasteczka
order={['accept', 'reject', 'settings']} // przyciski banera w tej kolejności
settings="modal" // ustawienia w oknie na środku (✕, Escape, klik w tło)
controls="switch" // przełączniki role="switch" zamiast checkboxów
settingsActions={['save', 'reject', 'accept']} // przyciski pod kategoriami
classNames={{ … }}
/>
```
Domyślnie (bez tych propsów) baner wygląda i działa jak przed 1.10.0.
### Duże okno ze szczegółami (`settings="detailed"`, 1.12.3)
Trzy tryby ustawień do wyboru w projekcie — jeden prop:
| `settings` | Co widzi użytkownik po „Ustawienia” |
|---|---|
| `'inline'` (domyślnie) | kategorie w samym pasku banera |
| `'modal'` | małe okno na środku: kategoria + krótki opis + przełącznik |
| `'detailed'` | duże okno: każda kategoria to karta z przełącznikiem, opisem i rozwijaną listą jej ciasteczek (nazwa, dostawca, cel, czas przechowywania) |
```tsx
<CookieBanner equalChoice controls="switch" settings="detailed" />
```
Lista ciasteczek bierze się z **Cookie Settings → Cookies** (to samo źródło co `<CookieTable>` na stronie
polityki), filtrowana po kategorii — kategoria bez wpisów nie ma rozwijanej listy. Podpisy listy: **Cookie
Settings → Detail labels** (`cookies` — np. „Używane ciasteczka”, licznik dopisuje się sam; `provider`, `purpose`,
`duration`), per język; puste → angielskie. `getConsentTexts` przekazuje to w `texts.cookies` / `texts.details`
— nic nie trzeba podawać w kodzie. Zamykanie jak w `'modal'` (✕, Escape, klik w tło). Domyślna szerokość okna
`max-w-4xl` — zmiana przez `classNames.dialog`.
Który tryb wybrać: decyduje design projektu. Brief milczy → `'detailed'` (użytkownik widzi przy zgodzie, jakie
ciasteczka i od kogo — pełna informacja w miejscu decyzji), pod warunkiem że lista Cookies jest wypełniona ze skanu
(`ipal-consent-check` → cookie-scan); pusta lista = okno bez rozwijanych list, wtedy wystarczy `'modal'`. Decyzję
zapisz w `AGENTS.md` → „Ustalenia projektu”.
Nie buduj własnego okna ani listy ciasteczek w projekcie (AGENT.md §7). Wygląd zmieniasz tokenami i `classNames`;
gdy potrzebujesz całkiem innego układu, dane są w kontekście: `useConsentContext()` → `texts.cookies`,
`texts.details`, `state`, `savePreferences`.
Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się nie pokazuje:
| Pole | Gdzie |
|---|---|
| `eyebrow` | mały napis nad tytułem banera („Prywatność i cookies”) |
| `title` | tytuł banera („Szanujemy Twoją prywatność”) |
| `settingsDescription` | opis pod tytułem ustawień |
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
| `detailLabels.cookies` / `.provider` / `.purpose` / `.duration` | podpisy listy ciasteczek w oknie `settings="detailed"` (puste → angielskie) |
| `cookies` (lista) | ciasteczka per kategoria — okno `detailed` i `<CookieTable>`; `purpose`, `duration` per język |
| `buttons.close` | etykieta przycisku ✕ dla czytników ekranu (puste → „Close”) |
| `buttons.savePreferences` | „Zapisz” w ustawieniach (do 1.11.0 pole `save` — nazwa zarezerwowana w Mongoose; w kodzie dalej `texts.buttons.save`). MongoDB: od 1.12.2 plugin przy starcie kopiuje stare `save` (wszystkie języki), gdy `savePreferences` brak |
Nowe pola w globalu = migracja w projektach na Postgres/SQLite (`payload migrate:create`); MongoDB bez zmian.
Elementy mają też stabilne uchwyty `data-ipal` do CSS i testów e2e (używa ich
`ipal-consent-check`): `banner`, `cookie-button` oraz przyciski `settings`, `reject`,
`accept`, `back`, `save`.
`accept`, `back`, `save`; w trybie modal także `consent-overlay`, `consent-dialog`, `close`; w trybie detailed
dodatkowo `category-<kategoria>` (karta) i `cookies` (rozwijana lista).
Dostępność: dialog banera i `CookieButton` mają `aria-label` z **Cookie Settings →
settingsTitle** (per język) — bez tekstów na sztywno w komponentach.
title** albo **settingsTitle** (per język) — bez tekstów na sztywno w komponentach. Modal ma
`aria-modal`, fokus na ✕ po otwarciu i zamyka się Escape; przełączniki mają `role="switch"` i `aria-checked`.
## Locale jako cookie functional (wbudowane)
@@ -184,6 +268,7 @@ Nie musisz nic konfigurować — działa out of the box:
```ts
const DEFAULT_COOKIE_MAP = {
functional: [LOCALE_COOKIE_NAME], // 'NEXT_LOCALE' — plugin zna własną cookie
analytics: [/* GA, Clarity, … */ 'ipal_vid'], // ipal_vid — statystyki w panelu (stats.md)
}
```
+50
View File
@@ -0,0 +1,50 @@
# Strona w budowie (narzędzie deweloperskie)
Tryb dla strony, która nie jest jeszcze gotowa: odwiedzający widzą tylko stronę główną i wybrane
podstrony (np. brief), a cała reszta jest zablokowana — bez zmian w kodzie, jednym przełącznikiem w panelu.
## Panel
**Site Settings → Under construction** (zakładka jest, gdy włączony moduł `pages`):
| Pole | Znaczenie |
|---|---|
| Site under construction | włącza tryb |
| Pages still available | strony, które dalej się otwierają; **strona główna jest dostępna zawsze** |
| Notice title / text / Close button label | treść popupu (per język) |
Lista stron i teksty pokazują się dopiero po zaznaczeniu przełącznika. Wyłączenie trybu przywraca
normalne działanie strony.
## Jak działa
- **Adres spoza listy** (także nieistniejący) → przekierowanie na stronę główną w tym języku z
`?notice=construction` (`createPageRoute` z opcją `redirect`). Strony dozwolone liczone są w
**każdym języku** (`/pl/brief` i `/en/project-brief`), więc przełącznik języka działa.
- **Kliknięcie linku** do strony spoza listy → `<ConstructionNotice>` anuluje przejście (przed
`next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"`
i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie.
- Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu.
- **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania
sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings).
## Wpięcie w projekcie
```tsx
// app/(frontend)/[locale]/[[...slug]]/page.tsx — redirect włącza blokadę adresów
import { notFound, permanentRedirect, redirect } from 'next/navigation'
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect })
// app/(frontend)/[locale]/layout.tsx — popup + przechwytywanie linków (bez stylów, classNames)
import { ConstructionNotice } from '@intecion/ipal-kit/client'
<ConstructionNotice
mode={await getConstructionMode(locale)} // z lib/content (createContentHelpers)
classNames={{ overlay: '…', dialog: '…', title: '…', message: '…', button: '…' }}
/>
```
`getConstructionMode(locale)` zwraca `{ enabled, allowedPaths, homePath, texts }` (typ
`ConstructionMode`). Czysta logika: `isPathAllowed(pathname, allowedPaths)`,
`constructionNoticeHref(homePath)`, stała `CONSTRUCTION_NOTICE_PARAM` (`@intecion/ipal-kit`).
Nowe pola w Site Settings = migracja w projekcie (`payload migrate:create`).
+1 -1
View File
@@ -224,7 +224,7 @@ round-trip do bazy i zwraca 200/503, więc Coolify/Docker odróżni „proces ż
od „app gotowa, baza dostępna":
```ts
// app/api/health/route.ts
// app/api/health/route.ts — zwykle: export { healthRoute as GET } from '@/lib/content'
import { createHealthRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health
+121 -101
View File
@@ -65,6 +65,15 @@ curl -s -o /dev/null -w "%{http_code}\n" \
https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit # 200
```
**Aktualizacja do najnowszej wersji:** `pnpm up --latest @intecion/ipal-kit`. Samo
`pnpm up @intecion/ipal-kit` nic nie zmieni, gdy `package.json` ma wersję dokładną
(`"1.8.13"`) — zostaje w zakresie. Potem sekcje „Wymaga zmian w projekcie” z CHANGELOG.
**401 przy pobieraniu paczki** (`ERR_PNPM_FETCH_401 … Unauthorized`) mimo publicznego
rejestru: w `~/.npmrc` jest stary `_authToken` dla `git.intecion.net`, a nieważny token
blokuje także odczyt. Usuń tę linię (token potrzebny tylko do publikacji, §8.3) albo
jednorazowo: `NPM_CONFIG_USERCONFIG=/dev/null pnpm up --latest @intecion/ipal-kit`.
---
## 2. NOWY PROJEKT — KOLEJNOŚĆ
@@ -106,7 +115,9 @@ export const i18nConfig = {
],
} as const satisfies I18nConfig
```
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` (i18n.md).
Strona jednojęzyczna: jeden locale, bez folderu `[locale]` — layout z `i18nConfig.defaultLocale`,
`createPageRoute` / `createNotFoundPage` bez zmian, Markdown w `app/md/[[...slug]]/route.ts` (i18n.md).
Nie zakładaj `[locale]` „na zapas” przy jednym języku — linki byłyby bez `/pl`, strony z `/pl`.
### 2.3 payload.config.ts
```ts
@@ -150,10 +161,11 @@ sprawdzić: **AGENT.md §0b**. Kod wszystkich tras niżej (§2.7–2.9).
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (za duże pliki, za zgodą); R2 przez `buildR2Storage(['media'], { s3Storage })` —
`s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md).
- Linki z pluginu (`buildLinkField`, `buildLinksField`, `resolveLinkHref` — links.md),
`src/fields/` (sectionHeader, sectionSettings) i `src/components/ui/`
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md`, reguły w AGENT.md §6.
- Pola z pluginu: linki (`buildLinkField`, `buildLinksField` — links.md), nagłówek i ustawienia
sekcji (`buildSectionHeaderField`, `buildSectionSettingsField` — blocks.md). W projekcie tylko
prymitywy wyglądu `src/components/ui/` (CMSLink na `resolveLink`, Button, Media, Section,
SectionHeader) i `src/components/forms/formClasses.ts` — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md` i `ipal-form/resources/`, reguły w AGENT.md §6.
Załóż je **przed** pierwszym blokiem.
### 2.5 Tailwind
@@ -207,36 +219,44 @@ layoutach i `not-found.tsx` **nie czytaj `headers()`** (AGENT.md §4.6).
### 2.7 Warstwa danych — jedno źródło
```ts
// src/lib/content.ts
// src/lib/content.ts — JEDYNE miejsce konfiguracji: dane, trasy, linki, layout
import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getPageJsonLd,
generatePageMetadata, getNotFoundPage, generateStaticParams, sitemap, robots,
// dane
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
// layout, formularze, linki
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav, getSystemLinks,
// trasy (re-eksport w app/)
sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
} = createContentHelpers({
config,
content: contentConfig,
i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
summaryField: 'aiSummary', // llms.txt i MCP biorą opis dla AI z buildSummaryField
mcp: { serverName: '<klient>-site' },
// pageJsonLd: { faq: (doc) => …mapowanie bloku FAQ na { question, answer }… },
// siteJsonLd: async ({ settings, baseUrl, locale }) => [buildLocalBusinessJsonLd({…})], // firma lokalna
})
```
Wszystko liczy się dopiero przy pierwszym użyciu i jest w cache na żądanie. Każdą
funkcję można pominąć i złożyć stronę z niższych klocków (`createPageMetadata`,
`createLlmsTxtRoute`, `createMcpRoute`… — seo.md, mcp.md) — plugin niczego nie wymusza.
### 2.8 Trasy
```tsx
// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import {
buildOrganizationJsonLd, buildWebSiteJsonLd, getAnalyticsConfig, getConsentTexts, getTurnstileConfig, sameAsUrls,
} from '@intecion/ipal-kit'
import { Analytics, ConsentProvider, CookieBanner, CookieButton, TurnstileProvider } from '@intecion/ipal-kit/client'
import { JsonLdGraph, MediaPreconnect } from '@intecion/ipal-kit/rsc'
import { i18nConfig } from '@/i18n.config'
import { getCachedPayload, getConfiguredLocales, getSettings } from '@/lib/content'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '@/lib/content'
import '../styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
@@ -244,88 +264,81 @@ type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
const payload = await getCachedPayload()
const [texts, analytics, turnstile, settings] = await Promise.all([
getConsentTexts({ config: i18nConfig, locale, payload }), // link do polityki — automatycznie (consent.md)
getAnalyticsConfig(payload),
getTurnstileConfig(payload), // siteKey tylko przy obu kluczach — inaczej widget i weryfikacja wyłączone
getSettings(locale),
])
const url = process.env.NEXT_PUBLIC_SERVER_URL
const name = typeof settings?.siteName === 'string' ? settings.siteName : undefined
// Dane z panelu; brak → węzeł pominięty (nigdy fallback z nazwą klienta). Firma lokalna: buildLocalBusinessJsonLd z globalu Company.
const schemas = name && url
? [buildWebSiteJsonLd({ name, url }), buildOrganizationJsonLd({ name, url, logo: settings.logo, sameAs: sameAsUrls(settings) })]
: []
// + buildNavigationJsonLd({ items: header.navItems, … }) z globala nagłówka (seo.md)
const shell = await getSiteShell(locale) // zgoda, analityka, Turnstile, JSON-LD strony, Site Settings
return (
<html lang={locale}>
{/* BEZ <head> — Next zarządza nim sam */}
<body>
<MediaPreconnect />
<JsonLdGraph schemas={schemas} />
<ConsentProvider texts={texts} logEndpoint="/api/ipal/consent">
<TurnstileProvider siteKey={turnstile.siteKey}> {/* zawsze — sam się wyłącza bez kluczy */}
<main>{children}</main>
</TurnstileProvider>
<CookieBanner equalChoice />
<CookieButton />
<Analytics {...analytics} /> {/* wewnątrz providera; opcja defer — analytics.md */}
</ConsentProvider>
<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
{/* <Header …/> */}
<main>{children}</main>
{/* <Footer …/> */}
</SiteProviders>
</body>
</html>
)
}
```
`SiteProviders` wpina w dobrej kolejności: `MediaPreconnect`, `JsonLdGraph` (WebSite + Organization
z Site Settings), `ConsentProvider` → `TurnstileProvider` (zawsze — sam się wyłącza bez kluczy) →
baner, `CookieButton`, `Analytics` (wewnątrz zgody). Nie dodaje żadnego markupu. Każdą część
zmienisz albo wyłączysz: `banner={<CookieBanner classNames={…} />}` / `false`, `cookieButton`,
`analytics={{ defer: true }}` / `false`, `jsonLd={[buildNavigationJsonLd(…)]}`, `cookieMap`,
`preconnect={false}`. Zupełnie własny układ: te same dane z `shell` do providerów (consent.md).
Okno ustawień zgody wybierasz propem `settings` banera: `'inline'` (domyślnie — kategorie w pasku),
`'modal'` (małe okno na środku) albo `'detailed'` (duże okno: każda kategoria z przełącznikiem, opisem i
rozwijaną listą ciasteczek z Cookie Settings → Cookies). Przykład:
`banner={<CookieBanner equalChoice controls="switch" settings="detailed" />}` — opis: consent.md → „Duże okno ze
szczegółami”.
```tsx
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy
import { notFound, permanentRedirect } from 'next/navigation'
import type { Metadata } from 'next'
import { JsonLdGraph, RenderBlocks } from '@intecion/ipal-kit/rsc'
import { resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
import { generatePageMetadata, getCachedPayload, getPageJsonLd, resolveRoute } from '@/lib/content'
import { sendForm } from '../actions'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny
export const revalidate = 3600 // ISR
export const revalidate = 3600 // ISR — literał w pliku (Next czyta go statycznie)
type Args = { params: Promise<{ locale: string; slug?: string[] }> } // bez searchParams!
// Ten sam cache co strona: jedno odczytanie ustawień i jedno resolveRoute na żądanie
export async function generateMetadata({ params }: Args): Promise<Metadata> {
const { locale, slug } = await params
return generatePageMetadata(locale, slug)
}
export default async function Page({ params }: Args) {
const { locale, slug } = await params
const route = await resolveRoute(locale, slug ?? [], 1)
if (!route) {
const target = await resolveRedirect({ payload: await getCachedPayload(), locale, segments: slug, config: i18nConfig })
if (target) permanentRedirect(target)
notFound()
}
const enhanceProps = () => ({ locale }) // locale dla CMSLink w blokach
const doc = route.doc as { layout?: unknown[] }
return (
<>
<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} /> {/* WebPage/BlogPosting, okruszki, FAQ */}
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
</>
)
}
const route = createPageRoute(content, {
blocks: blockRegistry,
notFound, permanentRedirect, // wstrzyknięte z next/navigation
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
// render: ({ route, blocks }) => route.type === 'archive' ? <Archive … /> : undefined,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // SSG → <head> synchroniczny
```
Opcje `resolveRedirect` (`collections`, `homeSlug`): content.md.
Archiwum z paginacją (`?page=`) — osobna trasa albo świadomie dynamiczna (pages.md).
`createPageRoute`: trasa (`resolveRoute`), stary slug → 308 (`resolvePageRedirect`), 404, metadata,
`generateStaticParams`, JSON-LD strony (`getPageJsonLd`, wyłączenie: `jsonLd: false`) i bloki z
`locale` + `blockProps`. Bez `searchParams` — archiwum z paginacją (`?page=`) to osobna trasa albo
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
404 z panelu: `src/app/(frontend)/[locale]/not-found.tsx` z `getNotFoundPage`
(przykład w pages.md).
```tsx
// src/app/(frontend)/[locale]/notFoundView.ts — treść 404 z panelu w jednym języku (server action, od 1.12.0)
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}
// src/app/(frontend)/[locale]/not-found.tsx — 404 w języku z URL, bez headers(); treść ładowana dopiero przy 404,
// a nie w danych RSC każdej strony (pages.md → „Dlaczego leniwy”)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
```ts
// Trasy SEO / GEO / ops — każda to re-eksport, konfiguracja jest w lib/content.ts
// src/app/sitemap.xml/route.ts — XML dla Google, wygląd dla ludzi z pluginu (nic w /public)
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
@@ -334,43 +347,29 @@ export const dynamic = 'force-dynamic'
export { robots as default } from '@/lib/content'
// src/app/manifest.ts
import { createManifestHandler } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
export { manifest as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
export default createManifestHandler({ getCachedPayload, config: i18nConfig })
// ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–7) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: to samo z `full: true`)
import { createLlmsTxtRoute } from '@intecion/ipal-kit'
// ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–8) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: llmsFullRoute)
export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, summaryField: 'aiSummary' })
// src/app/md/[locale]/[[...slug]]/route.ts — każda strona jako Markdown (noindex + canonical do HTML)
import { createMarkdownRoute } from '@intecion/ipal-kit'
import { contentConfig } from '@/content.config'
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
// src/app/indexnow-key.txt/route.ts — klucz IndexNow (z Site Integrations albo INDEXNOW_KEY)
import { createIndexNowKeyRoute } from '@intecion/ipal-kit'
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createIndexNowKeyRoute({ getCachedPayload })
// src/app/api/mcp/route.ts — publiczny serwer MCP (AI przegląda stronę)
import { createMcpRoute } from '@intecion/ipal-kit'
export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic'
const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig, content: contentConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: '<klient>-site', summaryField: 'aiSummary' })
export const POST = mcp.POST
export const GET = mcp.GET
// src/app/api/health/route.ts
import { createHealthRoute } from '@intecion/ipal-kit'
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload })
```
Jeden sitemap: `sitemap.xml/route.ts` **albo** `sitemap.ts` — nigdy oba. Nagłówek
sitemapy = „XML Sitemap”, pod nim „Technology by Intecion.com”; zmiana
@@ -409,7 +408,8 @@ pnpm dev
3. **Pages** — strona główna z tytułem **w każdym języku** (pusty slug EN = 404 na `/en`).
4. **Site Settings → System Pages** — Homepage (bez tego `/pl` → 404), 404,
polityki; archiwa kolekcji treści.
5. **Cookie Settings** — teksty banera per język.
5. **Cookie Settings** — teksty banera per język; **Cookies** (lista ze skanu, `ipal-consent-check`) i **Detail
labels** (podpisy listy w oknie `settings="detailed"`) — też w każdym języku.
6. **Notifications** — komunikaty formularzy per język.
7. **Site Integrations** — SMTP/Graph (From Name, From Address), Turnstile, ID
analityki/pikseli.
@@ -567,6 +567,25 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 25 | **1.9.1** — zgoda: wersja, rejestr, tabela | Cookie Settings → Policy version; `consentLog: true` + `logEndpoint`; `<CookieBanner equalChoice>`; skan + `<CookieTable>`; Postgres: `migrate:create` | consent.md |
| 26 | **1.9.1** — media: `priority`, brak placeholderów, `images` w next.config | `<Media>` przez `mediaImageProps`/`videoProps`, `buildMediaPlaceholderHook`, `buildImagesConfig`, `buildUploadSecurityHeaders` | storage.md |
| 27 | **1.9.1** — staging indeksowany | `IPAL_NOINDEX=1` w env stagingu | seo.md |
| 28 | **1.9.2** — własny `FormRenderer` (kopia silnika na `useForm`) | **bezpieczeństwo:** przekazywał do przeglądarki cały dokument formularza z zakładką Emails (adresy firmy w HTML). Blok → `<RenderForm form action locale texts classNames>`, wygląd do `formClasses.ts`, usuń `FormRenderer.tsx`; nietypowy formularz → `useBuilderForm` | forms.md |
| 29 | **1.9.2** — formularze krokowe / listy wyboru robione w kodzie | panel: bloki **Step**, **Radio**, **Checkbox group**, **Date**; Notifications → next / back / stepOf; Postgres: `migrate:create` | forms.md |
| 30 | **1.9.2** — layout składany ręcznie (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `<SiteProviders shell={await getSiteShell(locale)} …>` — te same opcje (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 |
| 31 | **1.9.2** — strona catch-all i `not-found.tsx` pisane ręcznie | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` z `/rsc`; `revalidate` zostaje literałem | pages.md |
| 32 | **1.9.2** — trasy llms/md/mcp/health/indexnow/manifest z konfiguracją w każdym pliku | re-eksport z `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` raz w `createContentHelpers` | PROGRAMISTA §2.7 |
| 34 | **1.11.0** — kopia `publicForm`, własny renderer pola z wariantem / kontekstem | `RenderForm values` albo `prepareBuilderForm` + `<BuilderForm values>`; usuń kopię | forms.md |
| 35 | **1.11.0** — dodatkowe relacje „kategorie” obok linków, linki do wpisów jako URL | `buildLinkField({ relationTo: ['pages', 'categories'] })` (migracja danych linków) | links.md |
| 36 | **1.11.0** — JSON-LD produktu / kategorii składany w projekcie, `jsonLd: false` | `pageJsonLd.entries` + `buildProductJsonLd`, z powrotem `jsonLd` w `createPageRoute` | seo.md |
| 37 | **1.11.0** — własny RenderBlocks w trasie strony tylko dla `h1` pierwszej sekcji; `storage` w `ipalEnvRules` warunkowany NODE_ENV; ręczne `remotePatterns` / `dangerouslyAllowLocalIP` dla localhost | `isFirst` z `createPageRoute`; `ipalEnvRules({ storage: true })`; `buildImagesConfig()` | pages.md, env.md, storage.md |
| 38 | **1.11.1** — `revalidatePath` owinięte warunkiem `process.env.NEXT_RUNTIME` (seed / `payload run` padał) | usuń warunek — hook sam pomija rewalidację poza Next; celowo: `context: { disableRevalidate: true }` | hooks.md |
| 39 | **1.11.1** — strażnik fokusu wokół `RenderForm` (strona przewijała się do formularza po powrocie) | usuń — `BuilderForm` przenosi fokus tylko przy zmianie kroku | forms.md |
| 40 | **1.11.1** — własny `ThemeScript` / przełącznik motywu / `useSyncExternalStore` na `data-theme` | `<SiteProviders theme>` (albo `<ThemeScript {...shell.theme}>`), `<ThemeSwitcher label={shell.theme.toggleLabel}>`, `useTheme`; ten sam klucz `ipal-theme` — wybór odwiedzających zostaje. Postgres: `migrate:create` (`system`, `themeToggleLabel`) | theme.md |
| 41 | **1.11.1** — własne `anchors.ts` / `TableOfContents` / konwerter nagłówków z `id` | `extractHeadings`, `<TableOfContents>` (`/client`), `RenderRichText headingIds`, `buildTableOfContentsField()` (ten sam kształt `show`/`label` — bez migracji danych) | richtext.md |
| 42 | **1.11.1** — `notFound` łapany w `page.tsx`, żeby przekierować na stronę główną | `createPageRoute(…, { redirect, onMissing: 'redirectHome' })` | pages.md |
| 43 | **1.11.1** — `<Media>` ustawia kolor tła tylko dla JPEG | usuń warunek — `mediaImageProps` robi to sam (`placeholderColor`) | storage.md |
| 44 | **1.11.1** — `CmsLink['appearance']` zastąpione własnym typem, bo typ zależał od kolejności pól | typy per kształt: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`; `pnpm generate:types` i popraw importy | links.md |
| 45 | **1.11.1** — opis formatu w etykiecie pola formularza / godzina jako tekst | pole **Placeholder** w panelu, typ **Time**; Postgres: `migrate:create` | forms.md |
| 46 | **1.12.3** — własne okno ustawień cookies / lista ciasteczek w banerze pisana w projekcie | `<CookieBanner settings="detailed">` (lista z Cookie Settings → Cookies, podpisy: Detail labels); usuń własną wersję; Postgres: `migrate:create` | consent.md |
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, ręczne `resolveLinkHref` w `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (ten sam kształt danych — bez migracji), `resolveNav`, `resolveLink` z `lib/content` | blocks.md, links.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
`node_modules/@intecion/ipal-kit/dist`.
@@ -619,6 +638,7 @@ grep -c "<symbol>" src/<ścieżka> # >0 — zmiana zapisana
# docs/: zmiana API/zachowania → zaktualizuj plik modułu W TYM SAMYM commicie
pnpm clean && pnpm build
grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!)
# docs/CHANGELOG.md: nowa sekcja ## <wersja> na górze (zostaje min. 20 ostatnich wersji)
git add -A && git commit -m "opis" # PRZED version (dist/ i tak jest ignorowany)
npm version <wersja> # numer podaje człowiek; minor = nowe API, major = łamiące
npm publish
+19 -20
View File
@@ -127,14 +127,13 @@ Sprawdź: lista języków istnieje tylko w `i18n.config.ts` (grep `'pl'` w `src`
```
Zrób zgodnie z AGENT.md §5.3 i §6.2:
1. src/fields/sectionHeader.ts, sectionSettings.ts — kod 1:1 z
node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-block/resources/kod-sekcji.md
(linki: buildLinkField/buildLinksField z @intecion/ipal-kit — nie kopiuj).
1. Wspólne pola sekcji i linki są w pluginie: buildSectionHeaderField, buildSectionSettingsField,
buildLinkField, buildLinksField z @intecion/ipal-kit — nie kopiuj, nie twórz src/fields/.
2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized,
normalizeFilenameHook, buildOptimizeUploadHook + buildOptimizeUploadField (storage.md); jeśli R2 — buildR2Storage(['media'], { s3Storage }) z env, s3Storage
wstrzyknięty z @payloadcms/storage-s3 (storage.md).
3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField,
layout typu blocks (na razie jeden blok Content: sectionHeaderField + content richText),
layout typu blocks (na razie jeden blok Content: buildSectionHeaderField + content richText),
trackSlugHistoryHook, buildRevalidateHook (hooks.md).
NIE twórz kolekcji users, settings, navigation ani żadnych innych.
Potem pnpm generate:types i payload generate:importmap.
@@ -167,12 +166,12 @@ Plan najpierw.
```
Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
- src/proxy.ts z createProxy, matcher jako literał inline,
- src/lib/content.ts z createContentHelpers (w tym getNotFoundPage, generateStaticParams),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, MediaPreconnect w body,
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera,
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams,
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków,
- [locale]/not-found.tsx z getNotFoundPage dla każdego języka + LocaleView, BEZ headers() (pages.md).
- src/lib/content.ts z createContentHelpers (PROGRAMISTA §2.7 — eksportuje też trasy, getSiteShell, resolveNav),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, <SiteProviders shell={await getSiteShell(locale)} …>
(zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności),
- [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
export const revalidate (literał), BEZ searchParams,
- [locale]/not-found.tsx: createNotFoundPage(content, { load: loadNotFoundView }) + notFoundView.ts ('use server', renderNotFoundView) — BEZ headers() (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
@@ -184,11 +183,11 @@ Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`
```
Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md:
- app/sitemap.xml/route.ts (sitemapRoute z lib/content), robots.ts, manifest.ts (createManifestHandler), llms.txt/route.ts,
- re-eksporty z lib/content: app/sitemap.xml/route.ts (sitemapRoute), robots.ts (robots), manifest.ts (manifest), llms.txt/route.ts (llmsRoute),
api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic',
- next.config.ts: htmlLimitedBots, buildSecurityHeaders,
- metadata strony przez generatePageMetadata z lib/content (wspólny cache), favicon przez buildIconsMetadata,
- JSON-LD w root layoucie: Organization + WebSite (seo.md) z danych z panelu,
- JSON-LD: Organization + WebSite daje SiteProviders z Site Settings; firma lokalna → siteJsonLd w createContentHelpers (seo.md),
- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) importowanym z @intecion/ipal-kit/env (env.md).
CSP jeszcze nie — będzie w kroku 14.
Plan najpierw.
@@ -207,7 +206,7 @@ Zrób wg AGENT.md §6.8, kod z node_modules/@intecion/ipal-kit/docs/agent/skills
- globals/Header.ts, Footer.ts (kod z §6.8),
- globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email —
wszystko localized tam, gdzie tekst,
- lib/navigation.ts (resolveNav), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- menu przez resolveNav z lib/content (plugin, NIE lib/navigation.ts), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- linki prawne w stopce z ról System Pages, NIE ręcznie,
- hook afterChange na globalach z revalidatePath('/', 'layout').
Podepnij w [locale]/layout.tsx. Etykiety a11y z panelu.
@@ -234,8 +233,8 @@ Skrót: `/ipal-block <Nazwa> — <pola z 9a>, <opis wyglądu / zrzut>`.
```
Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3):
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, buildLinksField, media, items,
sectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- src/blocks/<Nazwa>/config.ts: buildSectionHeaderField, buildLinksField, media, items,
buildSectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX,
powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9),
- dodaj do Pages.layout i do blocks/registry.ts,
@@ -253,11 +252,11 @@ Skrót: `/ipal-form <formularz, odbiorca zgłoszeń>`.
```
Zrób wg forms.md, turnstile.md, email.md:
- blok formularza korzystający z form-buildera pluginu (pola i teksty z panelu),
- logika przez useForm/useContactForm z @intecion/ipal-kit/client — bez ręcznego useState,
- blok formularza: <RenderForm> z @intecion/ipal-kit/rsc + formClasses.ts (skill ipal-form) — pola, kroki,
listy wyboru i teksty z panelu, żadnego własnego renderera,
- checkbox consent (zgoda RODO) z linkiem do polityki przez getSystemPagePath,
- TurnstileProvider w layoucie (siteKey z getSiteIntegrations) — bez przekazywania siteKey do bloku,
- honeypot, zdarzenie form_submit (formAnalyticsOnSuccess).
- Turnstile z SiteProviders w layoucie — bez przekazywania siteKey do bloku,
- honeypot i zdarzenie GTM z panelu robi RenderForm sam (forms.md).
Plan najpierw.
```
Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zgody → odrzucone.
@@ -268,7 +267,7 @@ Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zg
```
Zweryfikuj i dokończ wg consent.md i analytics.md:
- Analytics wewnątrz ConsentProvider, ID tylko z Site Integrations,
- Analytics przez SiteProviders (wewnątrz zgody), ID tylko z Site Integrations,
- czy włączyć defer (Core Web Vitals) — <tak/nie>,
- Meta Pixel: <w panelu | w GTM> (nigdy oba),
- link do polityki w banerze: automatyczny (bez parametru privacyPolicy w kodzie).
+1 -1
View File
@@ -88,7 +88,7 @@ przyciskiem Reveal/Hide. To maskowanie UI, NIE hashowanie ani szyfrowanie:
wartość w bazie jest plaintext (musi być odzyskiwalna do autentykacji SMTP/R2).
Chroni przed patrzeniem przez ramię i przypadkowym pokazaniem panelu.
Podpięte przez `admin.components.Field: '@intecion/ipal-kit/client#MaskedField'`.
Podpięte przez `admin.components.Field: '@intecion/ipal-kit/admin#MaskedField'`.
Działa na dowolnym polu `text`. Po wpięciu w projekcie może być konieczne
`payload generate:importmap`, żeby panel rozpoznał komponent.
+1
View File
@@ -49,6 +49,7 @@ używasz).
```ts
ipalEnvRules({
storage?: boolean, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_PUBLIC_URL)
// produkcja: wymagane; dev: opcjonalne (media na dysku), ale wszystkie albo żadne (1.11.0)
emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER)
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string },
serverUrlVar?: string, // domyślnie 'NEXT_PUBLIC_SERVER_URL'
+135 -5
View File
@@ -23,8 +23,8 @@ consent RODO, powiadomienia).
| własna walidacja/wysyłka | `submitForm` (Turnstile+consent+mail) |
| klient nie zmieni formularza | klient edytuje pola w panelu |
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → front pobiera
jego definicję → renderuje pola dynamicznie → wysyła przez `submitForm`. Pola,
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → blok renderuje go
przez `<RenderForm>` → wysyłka przez `sendForm` (`createSubmitAction` → `submitForm`). Pola,
etykiety, komunikaty, odbiorca — wszystko z panelu.
Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigurację
@@ -42,7 +42,8 @@ Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigu
ipalKit({
forms: {
redirectRelationships: ['pages'], // formularz może przekierować na Page
// fields: { text: true, textarea: true, email: true, ... }, // domyślnie włączone sensowne
// fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
// // time, select, radio, checkbox, checkboxGroup, message, step
},
})
```
@@ -53,6 +54,114 @@ Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions**
`forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej).
## Front — RenderForm (zalecane, jedna linia)
Cały front formularza z panelu jest w pluginie. Projekt ma blok i klasy:
```tsx
// src/blocks/FormBlock/Component.tsx
import { RenderForm } from '@intecion/ipal-kit/rsc'
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
```
- `form` — relacja z bloku (depth ≥ 1; ID albo null → nic się nie renderuje),
- `action` — `sendForm` z `createSubmitAction` (niżej), `texts` — `getFormTexts(locale)` z `lib/content`
(Notifications → Form messages),
- `classNames` — **jedyne** miejsce wyglądu (`src/components/forms/formClasses.ts`, szablon w ipal-form);
plugin nie ma żadnych stylów. Klucze: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- opcje: `requiredMark` (np. `" *"`), `converters` / `richTextClassName` (wygląd rich text),
`linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme`.
`RenderForm` (serwer) renderuje bloki **message** i potwierdzenie przez `RenderRichText`, wiąże
akcję z formularzem i językiem, rozwiązuje redirect i podaje przeglądarce **tylko publiczną część
formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładkę Emails (adresy firmy);
ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient).
### Typy pól w panelu
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea i number mają lokalizowane pole „Placeholder” — podpowiedź
w pustym polu („np. 10:00–12:00”). `BuilderForm` i `useBuilderForm` (`getInputProps`, `getTextareaProps`)
przekazują je same. Własny blok z tym polem: `withPlaceholder(block)` / `placeholderField` z roota;
blok godziny: `timeBlock`. Nowe pola w blokach formularzy = migracja (`pnpm payload migrate:create`).
| Typ | Wartość | Serwer sprawdza |
|---|---|---|
| radio, select | jedna wartość | tylko wartości z panelu |
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | prawdziwa data |
| time | `HH:MM` (`<input type="time">`) | godzina 00:00–23:59 |
| Step | — (podział) | nie jest polem |
### Formularz krokowy
Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym Step to ekran 1.
`BuilderForm`: „Krok 1 z 3” (`stepOf`), Dalej waliduje tylko bieżący krok, Wstecz zachowuje
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
### Pola i kroki warunkowe („Show only when”)
Każdy blok formularza (wbudowane, **Checkbox group**, **Step**, message) ma w panelu grupę
**Show only when** (`showWhen`): `field` — nazwa techniczna innego pola, `values` — wartości opcji
po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `field` = zawsze widoczne.
- Na polu: pole pokazuje się dopiero przy pasującej odpowiedzi (np. „Z czego wynika termin?”
tylko przy `deadline = fixed`).
- Na **Step**: cały krok (z polami) wypada, gdy warunek nie pasuje — kolejne kroki się przenumerowują
(„Krok 2 z 3”). Tak buduje się brief: ekran 1 wybiera obszary (Checkbox group), każdy następny
Step ma `showWhen: { field: 'areas', values: 'web' }`.
- Pole w ukrytym kroku jest ukryte, nawet gdy jego warunek pasuje; warunek wskazujący ukryte pole też
nie pasuje. Nazwa nieistniejącego pola (literówka) albo cykl ukrywa pole — widać to w podglądzie.
- Wspólna reguła `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — przeglądarka
(`useBuilderForm`/`BuilderForm`: co pokazać, walidować i wysłać) i serwer (`validateSubmission`):
ukryte pole **nie jest wymagane i nie jest zapisywane**, nawet gdy ktoś je dośle ręcznie.
Wyjątek: pole zgody RODO (`consent`) jest egzekwowane zawsze — warunkiem nie da się go wyłączyć.
- Typ `FieldCondition` (`{ field, values }`) dla własnego markupu na `useBuilderForm`; `splitSteps(fields, isShown)`
pomija ukryte pola i kroki, zachowując oryginalny `index` (bloki message renderują się po nim).
- Nowa grupa = kolumny `show_when_field` / `show_when_values` w tabelach bloków formularzy →
po aktualizacji wygeneruj migrację (`payload migrate:create`).
### Wartości pól ze strony (`values`, 1.11.0)
Strona zna wartość pola, której nie wpisuje odwiedzający — wybrany wariant produktu, kategorię, ofertę.
Redaktor dodaje w formularzu zwykłe pole tekstowe (np. `subject`, „Dotyczy”), a strona je wypełnia:
```tsx
// wartość znana na serwerze (kategoria „wkrótce”)
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} values={{ subject: category.title }} />
```
Pole z `values` jest pokazane tylko do odczytu (`<output>`, klasa `classNames.fixed`, `data-ipal="form-fixed"`),
wysyłane jak każde inne i walidowane przez serwer według definicji z panelu. Nazwy spoza formularza są pomijane.
Wartość jest w pierwszym HTML (SSR), nie dopiero po hydracji.
Wartość zmieniana w przeglądarce (konfigurator): serwer przygotowuje formularz `prepareBuilderForm` (`/rsc`) —
publiczną część (`publicForm`, bez zakładki Emails), wyrenderowane bloki message i potwierdzenie, akcję przypiętą
do formularza i języka, cel przekierowania — a komponent kliencki renderuje `BuilderForm` z aktualnym `values`:
```tsx
// serwer
const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale })
<Configurator form={form} texts={formTexts} />
// klient ('use client')
<BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
```
`publicForm(form)` (`/rsc`) — sama publiczna część dokumentu, gdy budujesz własny przekaz do klienta. Nigdy nie
przekazuj do przeglądarki surowego dokumentu formularza.
### Formularz nietypowy — bez kopiowania silnika
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
2. `useBuilderForm({ form, action, texts })` — cała logika, markup Twój: `steps`, `step`,
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
## Front — submitForm (server)
Wołasz w Server Action. Kształt pasuje 1:1 do `useForm` / `useContactForm`
@@ -131,7 +240,24 @@ email: mailAdapter(), // z '@intecion/ipal-kit' — SMTP albo Graph wg panelu
Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i
treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu.
`submitForm` odpowiada tylko za weryfikację Turnstile i zapis.
`submitForm` odpowiada tylko za weryfikację Turnstile i zapis. Zgłoszenie zapisuje w języku strony
(`locale` z `createSubmitAction`), więc form-builder bierze teksty maili i etykiety w tym języku.
### Ładne maile (`emailLayout`)
```ts
forms: { emailLayout: true } // opcjonalnie: beforeEmail: (emails, args) => emails (po layoucie)
```
- `{{*:table}}` zamienia się w **czytelne podsumowanie**: treść pytania zamiast nazwy pola, etykiety opcji
zamiast wartości (także Checkbox group), zaznaczony checkbox = ✓, puste odpowiedzi pominięte, grupy według
kroków (tytuły Step). Tylko pola, które odwiedzający widział (ukrytych warunkiem serwer nie zapisuje).
- Każdy mail dostaje **szablon** (tabele + inline CSS — Gmail, Outlook, Apple Mail): nagłówek z logo,
treść z panelu, stopka. Ustawienia: **Site Settings → Emails** — logo (**PNG/JPG**, SVG nie działa w
Gmailu/Outlooku; puste = nazwa strony), kolor akcentu (hex), stopka (per język). Link do strony i
absolutny adres logo z `serverURL` w `buildConfig` (ustaw go z `NEXT_PUBLIC_SERVER_URL`).
- Błąd przy składaniu szablonu nigdy nie blokuje wysyłki — idzie oryginalny mail, błąd w logu.
- Nowa zakładka = migracja w projekcie (`payload migrate:create`).
## Własne pola w kolekcji formularzy
@@ -283,7 +409,11 @@ To obsługuje WSZYSTKIE kody (w tym `consent`, `rate_limited`, `validation` z
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
## Logika klienta — useForm / useContactForm (bez markupu)
## Logika klienta — useForm / useContactForm (niższy poziom)
Dla formularzy z panelu używaj `RenderForm` / `useBuilderForm` (wyżej) — mają kroki, listy
wyboru i walidację z definicji pola. `useForm` to silnik pod spodem: dla formularza **spoza
buildera** (np. wyszukiwarka z filtrami), nie dla formularzy kontaktowych.
`submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w
każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit,
+5
View File
@@ -37,6 +37,11 @@ by wywaliło Payload przy generate:importmap / czystym Node). Projekt podaje.
Obsługuje: wszystkie języki, root (home), zmianę slug (rewaliduje stary I nowy
path — stary URL nie serwuje starej treści), delete.
**Poza serwerem Next** (1.11.1) hook nic nie robi: `pnpm payload run`, seed przez `tsx`, migracje —
brak `process.env.NEXT_RUNTIME`. Wcześniej Next rzucał `Invariant: static generation store missing`
i seed padał. Celowe pominięcie (masowy import w aplikacji): `context: { disableRevalidate: true }`
w wywołaniu Local API.
---
## setPublishedAtHook — auto-data publikacji
+52 -39
View File
@@ -24,6 +24,17 @@ Plugin ustawia `config.localization` z tego. Walidacja jest eager (fail-fast
przy starcie): pusta lista, duplikaty kodów, `defaultLocale` spoza listy,
zły format kodu → błąd `[ipal] i18n: ...`.
**`fallback: true` a zapis.** Odczyt w języku bez wartości daje wartość języka domyślnego —
i **zapis dokumentu utrwala ją**: zapis strony (w panelu albo `payload.update`) w dowolnym
języku zapisuje tekst PL w polach lokalizowanych, które w EN/DE były puste (np. pusty
`subheading` bloku dostaje polski). Skutki: niewidoczne braki tłumaczeń stają się polskim
tekstem na stronie EN/DE. Dlatego:
- tłumacz każde pole w każdym języku (nie licz na fallback),
- skrypty migracji/seedów czytają z `fallbackLocale: false` i zapisują tylko to, co ustawiają
(`context: { ipalSkipAutoFill: true }` — seo.md); dane do zmiany najpierw sprawdź na kopii bazy,
- `fallback: false` wyłącza i odczyt z języka domyślnego (puste pola na stronie EN/DE) —
świadoma decyzja projektu.
## Front — helpery
Wszystkie helpery są czyste (przyjmują config jako argument). Trzymaj swój
@@ -206,42 +217,38 @@ app/(frontend)/[locale]/
[[...slug]]/page.tsx # /pl/o-nas, /en/about
```
### Layout jednojęzyczny — locale z config
### Layout, strona, 404, Markdown — te same helpery, bez `[locale]`
```tsx
// app/(frontend)/layout.tsx (bez [locale])
// app/(frontend)/layout.tsx
import { i18nConfig } from '@/i18n.config'
export default async function Layout({ children }: { children: React.ReactNode }) {
const locale = i18nConfig.defaultLocale // stałe, nie z params
const settings = await getSettings(locale)
// ...reszta jak zwykle, ale locale jest stałe
return <html lang={locale}>...</html>
const locale = i18nConfig.defaultLocale // stałe, nie z params
return (
<html lang={locale}><body>
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent">{children}</SiteProviders>
</body></html>
)
}
// app/(frontend)/[[...slug]]/page.tsx — createPageRoute bierze język z config, gdy nie ma go w params
export const revalidate = 3600
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
// app/(frontend)/not-found.tsx (+ notFoundView.ts z server action — pages.md)
export default createNotFoundPage(content, { load: loadNotFoundView })
// app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
```
### Strony jednojęzyczne — locale z config
```tsx
// app/(frontend)/[[...slug]]/page.tsx (bez [locale])
import { i18nConfig } from '@/i18n.config'
export async function generateMetadata({ params }) {
const { slug } = await params // TYLKO slug, nie locale
const locale = i18nConfig.defaultLocale // stałe
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
}
export default async function Page({ params }) {
const { slug } = await params
const locale = i18nConfig.defaultLocale // stałe
const route = await resolveRoute(locale, slug ?? [], pageNum)
// ...
}
```
resolveRoute i inne helpery działają bez zmian — dostają stałe locale z config
zamiast z URL. Cała różnica to: brak `[locale]` w strukturze, locale z config.
Linki (`resolveLink`, `resolveNav`, `getSystemLinks`), sitemap, canonical, llms.txt i MCP dają adresy
bez `/pl` same — decyduje liczba języków w `i18n.config.ts`, nie struktura folderów.
(Trasa `md/[locale]/[[...slug]]` na stronie jednojęzycznej też obsłuży podstrony, ale nie `/md` —
dlatego tu `md/[[...slug]]`.)
### Middleware/proxy — jednojęzyczny prawie go nie potrzebuje
@@ -249,17 +256,19 @@ Dla jednego locale middleware jest pass-through (nic nie przekierowuje). Możesz
go pominąć albo zostawić — plugin i tak wykryje 1 locale i przepuści. Bez
przełącznika języka (jeden język), bez cookie NEXT_LOCALE (nie ma co pamiętać).
### Przejście jedno- → wielojęzyczny (later)
### Przejście jedno- → wielojęzyczny (później)
Jeśli klient później doda drugi język, to PRZEBUDOWA, nie przełącznik:
- dodaj locale do config
- przenieś strukturę do `[locale]/`
- layout/strony czytają locale z params
- wróci prefiks `/pl`, `/en` + hreflang
O prefiksie decyduje **liczba języków w `i18n.config.ts`**: jeden język = adresy bez `/pl` (linki,
sitemap, canonical), dwa i więcej = z prefiksem. Struktury `[locale]` przy jednym języku **nie
zakładaj na zapas** — plugin generowałby linki `/kontakt`, a strony byłyby pod `/pl/kontakt`.
Warto to przewidzieć na starcie: jeśli jest szansa na drugi język, rozważ od razu
strukturę wielojęzyczną (z [locale]), nawet dla jednego locale — wtedy prefiks
`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury.
Gdy klient doda drugi język:
1. dodaj język do `i18n.config.ts` (i `localization` w Payload przez `ipalKit`),
2. przenieś `app/(frontend)/*` do `app/(frontend)/[locale]/`, a `app/md/[[...slug]]` do `app/md/[locale]/[[...slug]]`,
3. layout bierze `locale` z `params` (PROGRAMISTA §2.8) — `createPageRoute` / `createNotFoundPage` bez zmian,
4. przetłumacz slugi i treści w panelu.
Linki, sitemap, hreflang i canonical przełączą się same. Stare adresy (`/kontakt`) proxy przekieruje
na `/pl/kontakt`, więc linki z Google i wizytówek dalej działają.
## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher)
@@ -307,6 +316,10 @@ fallback na root `/{code}`.
> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext
> (~150 linii) kopiowany w projektach.
Własny przełącznik (inny markup niż `LanguageSwitcher`): `useAlternateLinks()` (`/client`) zwraca
`{ [locale]: url }` bieżącej strony; `useSetAlternateLinks()` to setter, którego używa
`AlternateLinksUpdater` (zwykle niepotrzebny w projekcie).
## Next matcher — MUSI być literałem inline
Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy
+83 -6
View File
@@ -22,7 +22,7 @@ fields: [
| `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; `false` = bez pola |
| `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` |
@@ -51,10 +51,23 @@ puste → „Feature 02”. Komponent: `@intecion/ipal-kit/admin#RowLabel`. Zasa
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`**.
`appearance`. W `payload-types.ts` powstaje typ **`CmsLink`**; link bez stylu (`appearances: false`)
ma typ `CmsLinkPlain`, bez etykiety (`disableLabel`) — `CmsLinkNoLabel`, oba naraz — `CmsLinkPlainNoLabel`
(od 1.11.1; wcześniej wszystkie nazywały się `CmsLink` i typ zależał od kolejności pól). Każdy z nich
pasuje do `CmsLink`, więc `CMSLink` przyjmuje je bez zmian. Różne listy `appearances` albo `relationTo`
w jednym projekcie → nadaj własną nazwę: `buildLinkField({ interfaceName: 'CategoryLink', … })`.
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
@@ -69,11 +82,73 @@ 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}`.
## Render w projekcie
## Link gotowy do renderu — `resolveLink`
Komponent `CMSLink` jest w projekcie (wygląd przycisków to sprawa projektu) —
gotowy kod: [kod-sekcji.md](./agent/skills/ipal-block/resources/kod-sekcji.md). Menu: `resolveNav` w
`lib/navigation.ts` ([kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md)) korzysta z tego samego `resolveLinkHref`.
```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`
@@ -85,3 +160,5 @@ bazy nie jest potrzebna**:
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`).
+3
View File
@@ -35,6 +35,9 @@ odfiltrowane — ta sama zasada co sitemap/llms).
```ts
// app/api/mcp/route.ts
// Zwykle jedna linia (konfiguracja w createContentHelpers({ mcp: { serverName }, summaryField })):
// export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
// Niżej pełny wariant — gdy trasa potrzebuje opcji spoza lib/content.
import { createMcpRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
+4 -2
View File
@@ -16,7 +16,9 @@ Dzięki temu żaden komunikat nie jest zaszyty w kodzie — wszystko przez panel
Brak opcji — global **Notifications** jest zawsze budowany. Edytor zarządza
tekstami w panelu (karta Notifications), grupowane per kontekst. Grupa `form`:
`success`, `error`, `rateLimited`, `turnstile`, `validation`, `consent`,
`notFound`. Każde pole puste → fallback (NOTIFICATION_FALLBACK).
`notFound` oraz przyciski formularzy krokowych: `next` („Dalej”), `back` („Wstecz”),
`stepOf` („Krok {current} z {total}”). Każde pole puste → fallback (NOTIFICATION_FALLBACK, EN).
Dla formularzy: `getFormTexts(locale)` z `lib/content` = grupa `form` w danym języku.
## Helper — getNotificationTexts
@@ -25,7 +27,7 @@ Pobiera teksty z globala per język, fallback per pole. Analog `getConsentTexts`
```ts
import { getNotificationTexts } from '@intecion/ipal-kit'
const notifications = await getNotificationTexts({ payload, locale })
const notifications = await getNotificationTexts({ payload, locale }) // w lib/content: getFormTexts(locale) = .form
// notifications.form.error, notifications.form.success, ...
```
+63 -1
View File
@@ -62,7 +62,69 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt — `app/(frontend)/[locale]/not-found.tsx` (pełny plik):
Projekt — dwa pliki w `app/(frontend)/[locale]/` (od 1.12.0, **wariant leniwy — zalecany**):
```ts
// notFoundView.ts — server action z treścią 404 w JEDNYM języku
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export async function loadNotFoundView(locale: string) {
return renderNotFoundView(content, {
blocks: blockRegistry,
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
}, locale)
}
```
```tsx
// not-found.tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
```
(`fallback` z JSX → plik `notFoundView.tsx`.)
**Dlaczego leniwy:** Next wkłada drzewo `not-found` layoutu do danych RSC (`self.__next_f`) **każdej** strony
pod nim — router potrzebuje go do 404 po stronie klienta. Wariant natychmiastowy renderuje tam stronę 404 z panelu
w każdym języku, więc każda strona wiezie ją w HTML (404 = strona główna przy 2 językach: HTML strony głównej
195 → 146 KB gzip, strony kontaktu 153 → 104 KB). W wariancie leniwym w danych jest tylko `<NotFoundLoader>`
(`/client`); treść przychodzi z server action dopiero, gdy 404 się wyświetla. Język z adresu (`/en/...`);
`renderNotFoundView` przyjmuje tylko skonfigurowane języki (inne → domyślny). Status 404 bez zmian; treść
pojawia się po hydratacji (strona 404 i tak nie jest indeksowana).
Wariant natychmiastowy (do 1.11.x jedyny) — treść już w HTML, za cenę rozmiaru każdej strony:
```tsx
export default createNotFoundPage(content, { blocks: blockRegistry, fallback: <h1>404</h1> })
```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`).
Każdy blok strony dostaje `locale`, wynik `blockProps` i **`isFirst`** (1.11.0) — `true` dla pierwszej sekcji:
jej nagłówek jest jedynym `h1` strony (`<SectionHeader as={isFirst ? 'h1' : 'h2'}>`), pozostałe dają `h2`.
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
Opcja `redirect` (z `next/navigation`) włącza tryb „strona w budowie” — [construction.md](./construction.md).
**Brak strony → strona główna** (1.11.1): `onMissing: 'redirectHome'` (wymaga `redirect`) — adres bez strony
i bez starego sluga (np. wycofane `/pl/uslugi`) przekierowuje (307) na stronę główną w tym samym języku
(System Pages → Homepage). Bez przypisanej strony głównej albo gdy brakuje jej samej → zwykłe 404.
Domyślnie `'notFound'`; własna decyzja: `onMissing: ({ locale, segments }) => redirect(…)`.
```tsx
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect, onMissing: 'redirectHome' })
```
**Strona główna pod własnym slugiem** (1.12.2): `/pl/home` (slug strony przypisanej jako
Homepage) → 308 na `/pl` — jeden adres strony (canonical i tak wskazywał root; Search Console
zgłaszało duplikat). Wyłączenie: `createPageRoute(…, { homeAlias: false })`.
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
```tsx
import React from 'react'
+30
View File
@@ -53,6 +53,36 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta
(listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload.
## Spis treści i kotwice nagłówków (1.11.1)
Długie dokumenty (polityka prywatności, regulamin) — spis treści z linkami do sekcji.
Id nagłówków w spisie i w treści liczy ta sama funkcja, więc się nie rozjadą.
```tsx
// config bloku
import { buildTableOfContentsField } from '@intecion/ipal-kit'
fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }] // grupa tableOfContents: show, label
// komponent bloku (RSC)
import { extractHeadings, RenderRichText } from '@intecion/ipal-kit/rsc'
import { TableOfContents } from '@intecion/ipal-kit/client'
const items = block.tableOfContents?.show ? extractHeadings(block.content) : [] // [{ id, text, level }]
{items.length ? <TableOfContents items={items} label={block.tableOfContents?.label} classNames={tocClasses} /> : null}
<RenderRichText data={block.content} converters={converters} headingIds={{ className: 'scroll-mt-24' }} />
```
- `extractHeadings(content, { levels: ['h2'] })` — nagłówki w kolejności z tekstu; id = `toSlug(tekst)`,
powtórzenia `-2`, `-3`, puste nagłówki pomijane. Także z roota: `import { extractHeadings, headingText } from '@intecion/ipal-kit'`.
- `RenderRichText headingIds` — `true` (h2) albo `{ levels, className }`. Twój konwerter `heading` dalej
renderuje nagłówek; plugin dokłada `id` (i `className`, np. `scroll-mt-*` pod przyklejonym nagłówkiem).
- `<TableOfContents>` — bez stylów: `<nav aria-label={label}>` + `<ol>` linków. Serwer renderuje całą listę
(działa bez JS); w przeglądarce link czytanej sekcji dostaje `aria-current="location"` i `classNames.linkActive`.
`classNames`: `nav`, `label`, `list`, `item`, `link`, `linkActive`; `offset` (domyślnie 0.3 wysokości ekranu);
`data-ipal="toc"`, `data-level` na pozycjach.
- `buildTableOfContentsField()` — przełącznik „Show table of contents” + lokalizowana etykieta (typ `TableOfContentsSettings`).
Nowe pole w bloku = migracja (`pnpm payload migrate:create`).
## lexicalToMarkdown — richText → Markdown (dla AI)
Do czytelności dla agentów AI (Markdown per strona, llms-full) potrzebny jest
+4 -3
View File
@@ -120,13 +120,14 @@ const r2Url = process.env.R2_PUBLIC_URL || ''
const csp = [
"default-src 'self'",
// skrypty: self + Turnstile (Cloudflare) + analytics (GTM/GA jeśli używasz)
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://www.googletagmanager.com",
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
// style: self + inline (Tailwind) + Google Fonts
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
// obrazy: self + media R2 (z env!) + data:
`img-src 'self' data: ${r2Url}`.trim(),
`img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
"font-src 'self' https://fonts.gstatic.com data:",
"connect-src 'self' https://www.google-analytics.com",
// GA4: wildcardy obowiązkowe — ruch z UE idzie na region1.google-analytics.com
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
// ramki: Turnstile (widget captcha)
"frame-src https://challenges.cloudflare.com",
"form-action 'self'",
+72 -7
View File
@@ -25,15 +25,31 @@ ipalKit({
// generateDescription: ({ doc }) => doc.excerpt ?? '',
// fields: [...], // extra pola w grupie SEO
// autoFill: { title: 'title', description: 'excerpt' }, // mapowanie auto-fill
// autoFill: { content: 'blocks', descriptionLength: 155 }, // opis z innego pola bloków
// autoFill: false, // wyłącz auto-fill
// descriptionCheck: { settingsSlug: 'site-settings', siteDescriptionField: 'siteDescription' },
// descriptionCheck: false, // bez podpowiedzi pod opisem
},
})
```
Dodaje tab **SEO** do wskazanych kolekcji: title, description, image,
titleOverride. Auto-fill: hook `beforeChange` wypełnia puste `meta.title` z pola
dokumentu (domyślnie `title`). Nigdy nie nadpisuje tego, co edytor wpisał
ręcznie.
dokumentu (domyślnie `title`), a puste `meta.description` — z pola
`autoFill.description` (jeśli podane), inaczej z treści strony (bloki `layout` →
pierwsze akapity bez nagłówków, całe zdania do ~155 znaków). Nigdy nie nadpisuje
tego, co edytor wpisał ręcznie; przy częściowym zapisie (REST PATCH,
`payload.update` z kilkoma polami) czyta zapisany opis z dokumentu.
Skrypt, który ma zapisać dokładnie to, co ustawia (migracja danych, uzupełnianie pól na
produkcji): `payload.update({ …, context: { [SKIP_AUTO_FILL]: true } })` — `SKIP_AUTO_FILL`
(`'ipalSkipAutoFill'`) z `@intecion/ipal-kit` wyłącza auto-fill meta i `aiSummary` dla tego
zapisu (1.12.2).
Pod polem opisu w tabie SEO stoi podpowiedź (`MetaDescriptionCheck`, `/admin`):
opis pusty, taki sam jak `siteDescription` z Site Settings albo taki sam jak w innym
dokumencie kolekcji. Tylko informuje — zapisu nie blokuje. Długość pokazuje licznik
plugin-seo.
Tab budowany jest przez `injectSeoTabs`, nie przez `tabbedUI` plugin-seo —
tamten scala taby patrząc na pierwsze pole kolekcji i psuje się, gdy są tam już
@@ -415,7 +431,7 @@ klienta w fallbacku. Fallback z nazwą/kolorem klienta to ukryty hardkod.
> **Zalecane (aktualne): `createManifestHandler`** — to samo bez ręcznego kodu,
> z try/catch na brak bazy w buildzie:
> ```ts
> // app/manifest.ts
> // app/manifest.ts — zwykle: export { manifest as default } from '@/lib/content'
> import { createManifestHandler } from '@intecion/ipal-kit'
> import { getCachedPayload } from '@/lib/content'
> import { i18nConfig } from '@/i18n.config'
@@ -654,7 +670,36 @@ Działa automatycznie przez createPageMetadata (canonical + hreflang + x-default
- Redirect roota na twardo 301 do jednego języka → tracisz negocjację i drugą
wersję. Zostaw negocjację + hreflang.
## Sitelinks i structured data (branding w wynikach Google)
## Opisy w Google — data-nosnippet (stopka, dane kontaktowe)
Objaw: pod wynikiem i sitelinkami Google pokazuje adres, godziny i e-mail ze
stopki zamiast meta description — ten sam tekst pod każdą podstroną.
Przyczyna: Google sam wybiera tekst snippetu, gdy uzna, że pasuje do zapytania
lepiej niż description. Przy wyszukiwaniu marki „pasuje” blok kontaktowy, a stopka
jest na każdej stronie. Dobre, unikalne description tego nie wyłączy.
Rozwiązanie: tekst powtarzany na każdej stronie w `data-nosnippet`. Strona dalej
jest indeksowana, Google tylko nie cytuje tego fragmentu. Adres i godziny nadal ma
z JSON-LD `LocalBusiness`.
```tsx
import { NoSnippet } from '@intecion/ipal-kit/rsc' // w komponencie klienckim: /client
<footer>
<NoSnippet>…adres, godziny, telefon, linki…</NoSnippet>
</footer>
```
- Google honoruje `data-nosnippet` tylko na `div`, `section`, `span` — na `footer`,
`nav`, `aside` NIE. Dlatego `NoSnippet` renderuje `div` (`as="section"` /
`as="span"`), a `<footer>` zostaje na zewnątrz.
- Owiń: stopkę, pasek kontaktowy, sekcję CTA powtarzaną na każdej stronie
(„Umów się na konsultację”). **Nigdy `<main>`** — z niego ma pochodzić snippet.
- Komponenty pluginu robią to same: `CookieBanner`, `LanguageSwitcher`.
- Efekt po ponownym crawlu (dni–tygodnie). `ipal-seo-check` ostrzega o stopce bez
`data-nosnippet` i o zduplikowanych opisach.
Cel: żeby wyszukanie marki („rcustomcars") pokazało stronę główną + podlinki
(sitelinks) z opisami. Ważne — **sitelinków NIE DA SIĘ wymusić.** Google
@@ -735,6 +780,7 @@ Plugin dostarcza helpery — projekt MUSI je wpiąć i podać dane z panelu:
- [ ] `app/robots.ts` i `app/sitemap.ts` wystawione (patrz niżej — bez tego
Google nie widzi stron!)
- [ ] Jasne, opisowe tytuły stron (nie generyczne)
- [ ] Stopka i powtarzane bloki kontaktowe w `<NoSnippet>` (wyżej: „Opisy w Google”)
- [ ] Logiczna hierarchia + linkowanie wewnętrzne z głównej
Dane WSZĘDZIE z panelu (siteName, nav, logo), nigdy zaszyte.
@@ -947,7 +993,9 @@ globalnego siteDescription gdy pusty) — patrz niżej.
## Fallback meta description (siteDescription)
Strona bez `meta.description` → plugin używa globalnego `siteDescription` z
SiteSettings. Lepsze niż brak description (Google losowo wyciąga tekst ze strony).
SiteSettings. Lepsze niż brak description, ale ten sam opis na wielu stronach
Google ignoruje — dlatego auto-fill (wyżej) daje każdej stronie opis z jej treści,
a fallback zostaje dla stron bez treści w blokach.
- Pole **siteDescription** w SiteSettings → General (localized, textarea)
- buildMetadata: `meta.description || siteDescription`
@@ -1004,6 +1052,7 @@ fields: [ /* … */ buildSummaryField() ]
Potem wskaż je jako źródło opisu dla AI (preferowane nad meta.description):
```ts
createContentHelpers({ …, summaryField: 'aiSummary' }) // llmsRoute, llmsFullRoute, mcpGET/POST — raz
buildLlmsTxt({ …, summaryField: 'aiSummary' })
createLlmsTxtRoute({ …, summaryField: 'aiSummary' })
createSearchRoute({ …, summaryField: 'aiSummary' })
@@ -1021,7 +1070,7 @@ llmstxt.org) — agent dostaje całą stronę jednym żądaniem. Dołóż drugi
`full: true`:
```ts
// app/llms-full.txt/route.ts
// app/llms-full.txt/route.ts — zwykle: export { llmsFullRoute as GET } from '@/lib/content'
import { createLlmsTxtRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
@@ -1171,10 +1220,23 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
## 1.9.1 — dane strukturalne strony, IndexNow, sameAs, godziny otwarcia
- **`getPageJsonLd(locale, slug, { faq, pageType, entryType, breadcrumbs })`** z `createContentHelpers`:
- **`getPageJsonLd(locale, slug, { faq, pageType, entryType, breadcrumbs })`** z `createContentHelpers`
(węzeł strony składa `buildWebPageJsonLd` — dostępny też osobno dla własnych tras):
WebPage / CollectionPage / BlogPosting (język, `dateModified`, obraz), BreadcrumbList z prawdziwej
trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`:
`<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />`.
- **Wpisy, które nie są artykułami** (1.11.0): `pageJsonLd.entries` — główny węzeł per kolekcja zamiast
`BlogPosting`; okruszki i FAQ zostają z pluginu. Kontekst: `{ doc, url, image, description, siteName, archive, locale }`.
```ts
createContentHelpers({ pageJsonLd: { entries: {
products: ({ doc, url, image, siteName }) => buildProductJsonLd({ name: String(doc.title), sku: String(doc.sku), url, image, brand: siteName,
price: doc.price?.amount ? { amount: doc.price.amount, currency: doc.price.currency, kind: 'from' } : null }),
categories: ({ doc, url, description }) => buildWebPageJsonLd({ type: 'CollectionPage', name: String(doc.title), url, description }),
} } })
```
**`buildProductJsonLd({ name, url, sku, description, image, category, brand, price, availability })`** — Product;
`Offer` tylko z prawdziwą ceną z panelu (`kind: 'exact'` → `price`, `'from'` → `minPrice`); produkt „na zapytanie”
(bez ceny) nie dostaje `Offer` — szacowana cena w danych strukturalnych wprowadza w błąd.
- **`buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config, homeSlug })`** — nawigacja z
globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala:
`getLink` / `getChildren`.
@@ -1191,6 +1253,9 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
co. (ChatGPT Search, Copilot korzystają z indeksu Binga). Tylko produkcja z publicznym https.
Klucz: Site Integrations → IndexNow (generuje się przy zapisie) albo `INDEXNOW_KEY`. Google nie
obsługuje IndexNow — dla niego sitemap.
Trasa klucza z `lib/content`: `export { indexNowKeyRoute as GET } from '@/lib/content'`.
Ręcznie (np. import treści skryptem): `submitToIndexNow({ payload, urls })` (klucz: `getIndexNowKey(payload)`)
— nigdy nie rzuca, tylko loguje.
- **llms.txt / llms-full.txt** obejmują wpisy kolekcji treści (`content`) i wszystkie języki; MCP
`list_pages` też. Wspólne źródło: `collectSiteIndex`.
+120
View File
@@ -0,0 +1,120 @@
# stats
Wbudowane statystyki w panelu: **wizyty dziennie z ostatnich 30 dni**, najczęściej
oglądane strony, strony wejścia, źródła ruchu, urządzenia — oraz **historia
odwiedzającego**, ale tylko dla tych, którzy zgodzili się na cookies analityczne.
Dane zostają w bazie projektu; nic nie idzie do Google ani innych firm.
## Dwa poziomy — i dlaczego pierwszy nie wymaga zgody
| | Bez zgody (każdy odwiedzający) | Ze zgodą **analytics** (ta sama co GA4) |
|---|---|---|
| Co w przeglądarce | **nic** — żadnego cookie, localStorage, fingerprintu | cookie `ipal_vid` (losowe id, 180 dni) |
| Jak łączymy odsłony w wizytę | hash z losowej soli + IP + user agent; sól jest tylko w pamięci serwera i **wymieniana codziennie** — po północy nikt (także my) nie powiąże wizyty z IP ani z wizytą z innego dnia | jak obok + `visitorId` z cookie |
| Co widać w panelu | wykres dzienny, strony, wejścia, źródła, urządzenia, ścieżka w ramach jednej wizyty | dodatkowo **historia tej osoby przez wiele dni** |
| Zapisane IP / user agent | **nie** | **nie** |
- **Art. 399 Prawa komunikacji elektronicznej (ePrivacy 5(3))** wymaga zgody na zapis lub odczyt
informacji z urządzenia użytkownika. Poziom 1 niczego na urządzeniu nie zapisuje ani nie czyta,
więc baner go nie dotyczy.
- **RODO dalej obowiązuje** — IP jest przetwarzane przez chwilę przy liczeniu hasha. Podstawa: prawnie
uzasadniony interes (art. 6 ust. 1 lit. f). **Trzeba to opisać w polityce prywatności** (tekst niżej).
- **Poziom 2 bez zgody jest nielegalny** — `ipal_vid` tworzy `<PageStats>` dopiero po zgodzie na
analytics, a serwer i tak sprawdza cookie zgody (z aktualną *Policy version*) zanim zapisze
`visitorId`. Nie obchodź tego.
To nie jest porada prawna — przy nietypowym projekcie (dane wrażliwe, dzieci) skonsultuj z prawnikiem klienta.
## Config
```ts
ipalKit({
// …
stats: true,
// albo:
stats: {
retentionDays: 90, // ile dni trzymamy wizyty (domyślnie 90; wykres pokazuje 30)
timeZone: 'Europe/Warsaw', // gdzie zaczyna się „dzień” (domyślnie Europe/Warsaw)
dashboard: true, // wykres na dashboardzie panelu (domyślnie true)
},
})
```
Dodaje:
- kolekcję `stats-visits` (grupa *Statistics*, odczyt i usuwanie: admin; zapis tylko przez endpoint),
- `POST /api/ipal/hit`,
- widok **`/admin/stats`** + link w nawigacji (`StatsNavLink`),
- wykres 30 dni na dashboardzie (`StatsWidget`),
- `STATS_SLUG` (`'stats-visits'`) z `@intecion/ipal-kit` — do własnych zapytań.
Po włączeniu: `pnpm payload generate:importmap` (komponenty `@intecion/ipal-kit/admin#StatsView`,
`#StatsWidget`, `#StatsNavLink`) i migracja bazy (Postgres: `pnpm payload migrate:create`).
## Front
Z `SiteProviders`:
```tsx
<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" stats={{ locale }}>
```
Albo ręcznie — **wewnątrz `ConsentProvider`**:
```tsx
import { PageStats } from '@intecion/ipal-kit/client'
<PageStats locale={locale} /> // endpoint domyślnie '/api/ipal/hit'
```
`<PageStats>` wysyła jeden beacon na odsłonę (także przy nawigacji klienckiej Next). Nic nie renderuje.
`VISITOR_COOKIE` (`'ipal_vid'`) z `/client` — nazwa cookie, np. do własnej tabeli cookies.
CSP: endpoint jest na tej samej domenie — `connect-src 'self'` wystarcza.
## Czego nie liczymy
- zalogowanych użytkowników panelu (redaktor oglądający stronę nie zawyża statystyk),
- botów (Googlebot, podglądy linków, Lighthouse, curl, headless),
- prefetchu Next (`sec-purpose: prefetch`),
- odświeżenia tej samej strony w ciągu 10 s.
Zapisujemy samą ścieżkę: query string i `#hash` są odcinane (mogą zawierać e-mail, token, frazę
wyszukiwania). Referrer — tylko nazwa domeny. Kraj — tylko z nagłówka Cloudflare `cf-ipcountry`, jeśli jest.
## Wizyta
Ciąg odsłon z przerwami poniżej 30 minut, w ramach jednego dnia. Restart serwera albo kilka instancji
(każda ma własną sól) mogą rozbić trwającą wizytę na dwie — dla statystyk bez znaczenia. **Nie**
zapisuj soli w bazie, żeby to „naprawić”: wtedy wczorajsze hashe dałoby się odwrócić do IP.
Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę, przy pierwszej odsłonie).
## Prawa odwiedzającego (RODO)
- **Wycofanie zgody** — `useConsent` usuwa `ipal_vid` (jest w `DEFAULT_COOKIE_MAP.analytics`); kolejne
odsłony są już anonimowe.
- **Usunięcie danych** — odwiedzający podaje id z cookie `ipal_vid` (DevTools → Application →
Cookies). W panelu: *Statistics → Visits*, filtr `visitorId` = id → zaznacz wszystko → Delete.
Widok `/admin/stats?visitor=<id>` pokazuje to samo jako historię.
- Wizyt anonimowych nie da się przypisać osobie — nie ma czego wydać ani usunąć na żądanie.
## Do polityki prywatności i tabeli cookies
Dopisz w **Cookie Settings → Cookies** (panel) wiersz:
| Nazwa | Dostawca | Kategoria | Cel | Czas |
|---|---|---|---|---|
| `ipal_vid` | ta strona | analytics | Rozpoznanie powracającego odwiedzającego w statystykach strony | 180 dni |
Tekst do polityki prywatności (dopasuj nazwę administratora i okres):
> **Statystyki odwiedzin.** Liczymy odwiedziny strony własnym narzędziem, bez udziału podmiotów
> trzecich. Bez Twojej zgody nie zapisujemy niczego na Twoim urządzeniu: kolejne odsłony łączymy w
> wizytę za pomocą jednodniowego, nieodwracalnego skrótu adresu IP i typu przeglądarki; samego adresu
> IP nie przechowujemy, a skrót traci znaczenie po upływie doby. Zapisujemy odwiedzone podstrony,
> czas, domenę strony odsyłającej, rodzaj urządzenia (komputer / telefon / tablet) i język.
> Podstawą jest nasz prawnie uzasadniony interes (art. 6 ust. 1 lit. f RODO) — wiedza, jak
> korzystacie ze strony. Jeśli zgodzisz się na cookies analityczne, zapiszemy cookie `ipal_vid` z
> losowym identyfikatorem, dzięki któremu zobaczymy Twoje kolejne wizyty jako jedną historię
> (podstawa: zgoda, art. 6 ust. 1 lit. a RODO; możesz ją wycofać w ustawieniach cookies). Dane
> przechowujemy przez 90 dni.
+39 -1
View File
@@ -61,6 +61,16 @@ działa tylko bez env R2.
- **Brak zmiennych** → fallback na lokalny dysk (dev działa bez R2, zero konfiguracji).
- **Część zmiennych** → ostrzeżenie w logu + fallback (częściowa konfiguracja =
pewnie pomyłka).
- **Tylko `R2_PUBLIC_URL`** (absolutny, poza produkcją) → **media tylko do odczytu** (1.12.2):
adresy plików z domeny mediów, upload i usuwanie zablokowane (403). Do lokalnego deva
podpiętego pod bazę produkcyjną — widać obrazy, a nic nie trafia do prawdziwego bucketa.
**Import map nie zależy od env (1.12.2).** Gdy projekt wstrzykuje `s3Storage`, adapter jest
rejestrowany zawsze — bez R2 jako wyłączony (`enabled: false`, dysk lokalny). storage-s3 i tak
dopisuje wtedy swój `S3ClientUploadHandler` do import mapy, więc `pnpm dev` /
`generate:importmap` bez `R2_*` zapisuje ten sam `importMap.js` co produkcja. Do 1.12.1 dev bez
R2 usuwał ten wpis, a produkcyjny panel (z R2) renderował **pustą stronę** bez błędu w konsoli.
`ipal-audit` zgłasza import mapę bez handlera.
To wzorzec „degrade gracefully" — jak mailAdapter, który wraca do SMTP, gdy brak
Graph. Projekt działa niezależnie od tego, czy R2 jest skonfigurowany.
@@ -132,6 +142,27 @@ ustawiona). Bez niej Payload zwróci URL wskazujący na prywatny endpoint S3 →
Bez tego media wgrają się do R2, ale front pokaże 403. Konfiguracja domeny jest
po stronie Cloudflare, publiczny URL po stronie projektu (.env).
### Pamięć podręczna mediów (Cache Rule — obowiązkowo)
Pliki w R2 nie mają nagłówka `Cache-Control`: `@payloadcms/storage-s3` przy wysyłce ustawia tylko
`ContentType` i `ACL`, bez opcji na nagłówki. Cloudflare daje wtedy przeglądarce domyślne **4 h** —
Lighthouse: „Używaj efektywnego czasu przechowywania w pamięci podręcznej” (wideo, logo, tła pobierane od
nowa przy każdej wizycie po 4 h). Nazwy plików są stałe (nowa wersja = nowy plik z `normalizeFilename`),
więc długi czas jest bezpieczny.
Cloudflare → strefa domeny → **Caching → Cache Rules → Create rule**:
- *When incoming requests match*: `Hostname` equals `media.klient.pl` (domena z `R2_PUBLIC_URL`);
- *Cache eligibility*: Eligible for cache;
- *Edge TTL*: Ignore cache-control header and use this TTL → **1 year**;
- *Browser TTL*: Override origin and use this TTL → **1 year**.
Sprawdzenie (po kilku minutach):
```bash
curl -sI https://media.klient.pl/<plik> | grep -iE 'cache-control|cf-cache-status'
# cache-control: max-age=31536000 cf-cache-status: HIT (przy drugim zapytaniu)
```
Podmiana pliku pod TĄ SAMĄ nazwą (rzadkie — panel nadaje nową) wymaga Caching → Purge → Custom (URL).
## Migracja istniejących mediów
Jeśli projekt miał media lokalnie i przełączasz na R2 — nowe uploady idą do R2,
@@ -315,9 +346,16 @@ env, komponent podąża automatycznie.
- `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu,
`lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point →
`object-position`, placeholder blur + kolor. `MEDIA_SIZES` — podpowiedzi `sizes`.
Kolor tła (`style.backgroundColor`) zostaje na `<img>` po załadowaniu, więc od 1.11.1 tylko dla JPEG
(`placeholderColor: 'auto'`) — przezroczyste PNG/SVG/WebP (logotypy, ikony) nie mają już tła.
`placeholderColor: true` wymusza kolor (nieprzezroczyste PNG/WebP), `false` wyłącza. Hook nie zapisuje
koloru dla obrazów z przezroczystością (`color: null`).
- `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`.
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
uploadzie przez `sharp` z configu. Postgres: `migrate:create`.
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`).
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`). Poza produkcją
(1.11.0) także media serwowane przez aplikację — `/api/media/file/**` na `NEXT_PUBLIC_SERVER_URL` (dysk lokalny,
bez R2) — i `dangerouslyAllowLocalIP` dla localhost (Next 16 inaczej odrzuca prywatne IP). Opcje: `serverUrl`,
`production`, `publicUrl`, `extraHosts`.
- `<YouTubeEmbed videoId title playLabel note poster>` z `/client` — iframe po kliknięciu.
- `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów).
+85
View File
@@ -0,0 +1,85 @@
# Motyw jasny / ciemny (1.11.1)
Logika motywu z pluginu, wygląd w projekcie. Plugin daje: skrypt przed malowaniem (bez mignięcia
jasnego motywu), przełącznik bez stylów, hook `useTheme`, pola w Site Settings → Theme i motyw
widżetu Turnstile zgodny ze stroną.
## Jak to działa
- Strony są ISR/SSG — jeden HTML dla wszystkich, więc motyw **nie** trafia do HTML z serwera.
- `<ThemeScript>` (skrypt inline, pierwsze dziecko `<body>`) ustawia `data-theme="light|dark"` i
`color-scheme` na `<html>` przed pierwszym malowaniem.
- Kolejność: wybór odwiedzającego z `localStorage` (klucz `ipal-theme`, tylko gdy „Allow theme toggle”)
→ Site Settings → Default theme → przy `System` ustawienie urządzenia (`prefers-color-scheme`).
- `localStorage`, nie cookie: to preferencja interfejsu, nie śledzi i nie wymaga zgody.
- Zmiana w jednej karcie przechodzi do pozostałych (zdarzenie `storage`).
## Site Settings → Theme
| Pole | Znaczenie |
|---|---|
| `defaultTheme` | `light` · `dark` · `system` (od 1.11.1) |
| `allowThemeToggle` | pokazuj przełącznik; wybór odwiedzającego jest pamiętany |
| `themeToggleLabel` | nazwa przełącznika dla czytników ekranu, np. „Tryb ciemny” (localized, od 1.11.1) |
`getSiteShell(locale).theme` → `{ defaultTheme, allowToggle, toggleLabel }` (`themeConfigFrom(settings)` z roota).
## Podpięcie
```tsx
// src/app/(frontend)/[locale]/layout.tsx
const shell = await getSiteShell(locale)
return (
<html lang={locale} suppressHydrationWarning>
<body>
<SiteProviders shell={shell} theme> {/* theme → <ThemeScript> na początku */}
<Header themeLabel={shell.theme.allowToggle ? shell.theme.toggleLabel : null} … />
…
```
Bez `SiteProviders`: `import { ThemeScript } from '@intecion/ipal-kit/rsc'` i `<ThemeScript {...shell.theme} />`
jako pierwsze dziecko `<body>`. `suppressHydrationWarning` na `<html>` jest potrzebne — atrybut różni się
od HTML z serwera celowo.
```tsx
// przełącznik ('use client' albo w RSC — sam jest komponentem klienckim)
import { ThemeSwitcher } from '@intecion/ipal-kit/client'
<ThemeSwitcher
label={themeLabel}
classNames={{
root: 'inline-flex rounded-full border p-0.5',
light: 'rounded-full p-2 bg-white dark:bg-transparent',
dark: 'rounded-full p-2 dark:bg-surface-raised',
}}
// renderIcon={(t) => (t === 'light' ? <SunIcon /> : <MoonIcon />)} // domyślnie lucide Sun / Moon
/>
```
`<button role="switch" aria-checked>` (zaznaczony = ciemny). Który przycisk wygląda na aktywny, ustala CSS
z atrybutu na `<html>` (`dark:`), nie stan Reacta — po hydratacji nic nie przeskakuje.
Haki: `data-ipal="theme-switch"`, `data-ipal-theme-icon="light|dark"`.
Własny przełącznik: `useTheme()` → `{ theme, setTheme, toggle }` (`theme` = `null` na serwerze);
`applyTheme(theme, { persist, transitionMs })`, `readDocumentTheme()`, stałe `THEME_ATTRIBUTE`,
`THEME_STORAGE_KEY`, `THEME_SWITCHING_ATTRIBUTE`, `isTheme` z `/client`. Z roota także
`isThemeSetting` i `themeScript({ allowToggle, defaultTheme })` (sam tekst skryptu).
## CSS (Tailwind 4)
```css
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
/* płynne przejście kolorów tylko w chwili przełączenia (applyTheme: data-theme-switching, 300 ms) */
[data-theme-switching] *, [data-theme-switching] *::before, [data-theme-switching] *::after {
transition: background-color 0.3s, border-color 0.3s, color 0.3s, fill 0.3s !important;
}
```
Tokeny ciemnego motywu (`surface`, `fg`…) zostają w `styles.css` projektu.
## Turnstile
`BuilderForm` / `RenderForm` → `turnstileTheme` domyślnie `'page'`: widżet bierze motyw strony
(`data-theme`); bez motywu strony — `'auto'` (motyw urządzenia), jak przed 1.11.1. Zmiana motywu
rysuje widżet od nowa (token trzeba zdobyć ponownie). Stały motyw: `turnstileTheme="light"`.
+3
View File
@@ -116,6 +116,9 @@ przekazywania siteKey do każdego formularza.
### 1. Provider w layoutcie (raz, siteKey z serwera)
Z `SiteProviders` (PROGRAMISTA §2.8) provider jest już wpięty — klucz z `getSiteShell(locale).turnstileSiteKey`,
widget renderuje `RenderForm` na ostatnim kroku formularza. Ręcznie:
```tsx
// app/(frontend)/[locale]/layout.tsx (server)
import { getTurnstileConfig } from '@intecion/ipal-kit'
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.9.1",
"version": "1.12.3",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -57,6 +57,9 @@
"docs",
"bin"
],
"sideEffects": [
"**/*.css"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
@@ -87,6 +90,7 @@
},
"peerDependencies": {
"@clocklimited/payload-2fa": "^3.0.0-0",
"@payloadcms/next": "^3.90.2",
"@payloadcms/plugin-form-builder": "^3.90.2",
"@payloadcms/plugin-seo": "^3.90.2",
"@payloadcms/richtext-lexical": "^3.90.2",
+11 -4
View File
@@ -1,10 +1,17 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
* Admin-panel UI components (white-label branding, array row labels, integration fields and
* banners). Separate export so Payload's importMap can resolve them by a stable path, and so
* nothing importing @payloadcms/ui ends up in /client — that entry ships to every site visitor.
*/
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
export { StatsNavLink } from '../modules/stats/admin/StatsNavLink.js'
export { StatsView } from '../modules/stats/admin/StatsView.js'
export { StatsWidget } from '../modules/stats/admin/StatsWidget.js'
+32 -6
View File
@@ -1,6 +1,4 @@
'use client'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
@@ -23,10 +21,27 @@ export {
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
BuilderOption,
BuilderStep,
FieldCondition,
} from '../modules/forms/builderTypes.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useBuilderForm } from '../modules/forms/useBuilderForm.js'
export type { BuilderFormApi, UseBuilderFormOptions } from '../modules/forms/useBuilderForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
@@ -60,9 +75,20 @@ export {
useSetAlternateLinks,
} from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js'
export { TableOfContents } from '../modules/richtext/TableOfContents.js'
export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js'
export { NoSnippet } from '../modules/seo/NoSnippet.js'
export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
export { PageStats, VISITOR_COOKIE } from '../modules/stats/client.js'
export type { PageStatsProps } from '../modules/stats/client.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { isTheme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from '../modules/theme/theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from '../modules/theme/theme.js'
export { ThemeSwitcher } from '../modules/theme/ThemeSwitcher.js'
export type { ThemeSwitcherClassNames, ThemeSwitcherProps } from '../modules/theme/ThemeSwitcher.js'
export { applyTheme, readDocumentTheme, useTheme } from '../modules/theme/useTheme.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps, TurnstileTheme } from '../modules/turnstile/client.js'
+13
View File
@@ -14,7 +14,20 @@ export type {
} from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js'
export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute, renderNotFoundView } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, NotFoundViewOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { extractHeadings } from '../modules/richtext/headings.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
export { NoSnippet } from '../modules/seo/NoSnippet.js'
export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'
export { ThemeScript } from '../modules/theme/ThemeScript.js'
export type { ThemeScriptProps } from '../modules/theme/ThemeScript.js'
+55 -2
View File
@@ -22,6 +22,22 @@ export const cookieSettingsFields: Field[] = [
min: 1,
required: true,
},
{
name: 'eyebrow',
type: 'text',
admin: {
description: 'Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.',
},
localized: true,
},
{
name: 'title',
type: 'text',
admin: {
description: 'Banner heading, e.g. "We respect your privacy". Empty → not shown.',
},
localized: true,
},
{
name: 'message',
type: 'textarea',
@@ -38,6 +54,22 @@ export const cookieSettingsFields: Field[] = [
},
localized: true,
},
{
name: 'settingsDescription',
type: 'textarea',
admin: {
description: 'Intro under the settings heading — what cookies are for and that the choice can be changed later.',
},
localized: true,
},
{
name: 'alwaysActiveLabel',
type: 'text',
admin: {
description: 'Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.',
},
localized: true,
},
{
name: 'privacyLinkLabel',
type: 'text',
@@ -57,8 +89,29 @@ export const cookieSettingsFields: Field[] = [
{ name: 'acceptAll', type: 'text', localized: true },
{ name: 'reject', type: 'text', localized: true },
{ name: 'settings', type: 'text', localized: true },
{ name: 'save', type: 'text', localized: true },
// Not `save`: Mongoose reserves that path name and warns on every start/build.
{ name: 'savePreferences', type: 'text', label: 'Save', localized: true },
{ name: 'back', type: 'text', localized: true },
{
name: 'close',
type: 'text',
admin: { description: 'Screen-reader label of the ✕ button in the settings dialog.' },
localized: true,
},
],
},
{
name: 'detailLabels',
type: 'group',
admin: {
description:
'Labels of the cookie list in the detailed settings window (CookieBanner settings="detailed"). The list itself comes from Cookies below.',
},
fields: [
{ name: 'cookies', type: 'text', admin: { description: 'Expander under each category, e.g. "Cookies used" — the count is added.' }, localized: true },
{ name: 'provider', type: 'text', localized: true },
{ name: 'purpose', type: 'text', localized: true },
{ name: 'duration', type: 'text', localized: true },
],
},
{
@@ -83,7 +136,7 @@ export const cookieSettingsFields: Field[] = [
type: 'array',
admin: {
description:
'Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.',
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.',
initCollapsed: true,
},
fields: [
@@ -0,0 +1,39 @@
import type { BasePayload } from 'payload'
type MongoGlobals = {
collection?: {
updateOne: (
filter: Record<string, unknown>,
update: Record<string, unknown>[],
) => Promise<{ modifiedCount?: number }>
}
}
/**
* 1.11.1 renamed Cookie Settings `buttons.save` → `buttons.savePreferences` (Mongoose
* reserves `save`). MongoDB keeps the old key, but the first save of the global — panel
* or script — rewrites the document without it, and the button text silently falls back
* to "Save preferences" in every language. Runs once per start: copies the old value
* (all locales at once) into the new field when the new one is still missing.
* SQL adapters: the column rename happens in the migration (`migrate:create` → rename).
*/
export async function migrateCookieSettingsSaveButton(payload: BasePayload): Promise<void> {
if (payload.db.name !== 'mongoose') {return}
const globals = (payload.db as unknown as { globals?: MongoGlobals }).globals
if (!globals?.collection) {return}
try {
const result = await globals.collection.updateOne(
{
'buttons.save': { $exists: true },
'buttons.savePreferences': { $exists: false },
globalType: 'cookie-settings',
},
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
)
if (result.modifiedCount) {
payload.logger.info('[ipal] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).')
}
} catch (error) {
payload.logger.error({ err: error, msg: '[ipal] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' })
}
}
+23
View File
@@ -69,6 +69,29 @@ export const notificationsFields: Field[] = [
admin: { placeholder: 'This form is no longer available.' },
localized: true,
},
{
type: 'row',
fields: [
{
name: 'next',
type: 'text',
admin: { description: 'Step-by-step forms: button to the next step.', placeholder: 'Next', width: '33%' },
localized: true,
},
{
name: 'back',
type: 'text',
admin: { description: 'Step-by-step forms: button to the previous step.', placeholder: 'Back', width: '33%' },
localized: true,
},
{
name: 'stepOf',
type: 'text',
admin: { description: 'Progress — {current} and {total} are replaced.', placeholder: 'Step {current} of {total}', width: '34%' },
localized: true,
},
],
},
],
label: 'Form messages',
},
+2 -2
View File
@@ -64,7 +64,7 @@ export const smtpFields: Field[] = [
description: 'SMTP account password.',
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
components: {
Field: '@intecion/ipal-kit/client#MaskedField',
Field: '@intecion/ipal-kit/admin#MaskedField',
},
},
},
@@ -87,7 +87,7 @@ export const smtpFields: Field[] = [
type: 'ui',
admin: {
components: {
Field: '@intecion/ipal-kit/client#TestEmailButton',
Field: '@intecion/ipal-kit/admin#TestEmailButton',
},
},
},
@@ -27,7 +27,7 @@ export const turnstileFields: Field[] = [
description: 'Secret key used for server-side verification.',
// Masked in the UI (••••) — stored plaintext, readable for verification.
components: {
Field: '@intecion/ipal-kit/client#MaskedField',
Field: '@intecion/ipal-kit/admin#MaskedField',
},
},
},
+12 -1
View File
@@ -12,12 +12,13 @@ export const themeFields: Field[] = [
name: 'defaultTheme',
type: 'select',
admin: {
description: 'Theme applied on a visitor’s first visit.',
description: 'Theme applied on a visitor’s first visit. System = the visitor’s device setting.',
},
defaultValue: 'light',
options: [
{ label: 'Light', value: 'light' },
{ label: 'Dark', value: 'dark' },
{ label: 'System', value: 'system' },
],
required: true,
},
@@ -29,4 +30,14 @@ export const themeFields: Field[] = [
},
defaultValue: true,
},
{
name: 'themeToggleLabel',
type: 'text',
admin: {
condition: (data) => Boolean(data?.allowThemeToggle),
description: 'Name of the switch read by screen readers, e.g. "Dark mode".',
},
label: 'Toggle label',
localized: true,
},
]
+8
View File
@@ -6,6 +6,10 @@ import { themeFields } from './fields/theme.js'
type BuildSiteSettingsArgs = {
/** Extra fields injected by the client project */
additionalFields?: Field[]
/** "Under construction" tab (developer tool) — given when the pages module is on. */
constructionFields?: Field[]
/** "Emails" tab — given with `forms: { emailLayout: true }`. */
emailFields?: Field[]
/**
* Fields for the "System Pages" tab — page assignments by role (homepage,
* privacy policy, collection archives). Assembled by the caller, which is the
@@ -30,6 +34,8 @@ type BuildSiteSettingsArgs = {
*/
export function buildSiteSettings({
additionalFields,
constructionFields,
emailFields,
systemPageFields,
}: BuildSiteSettingsArgs = {}): GlobalConfig {
return {
@@ -55,6 +61,8 @@ export function buildSiteSettings({
...(systemPageFields?.length
? [{ fields: systemPageFields, label: 'System Pages' }]
: []),
...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []),
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
],
},
+25 -5
View File
@@ -19,6 +19,9 @@ export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
// Shared section fields (header: eyebrow/heading/intro, settings: anchor/background).
export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -39,6 +42,9 @@ export {
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
archiveFieldName,
@@ -74,6 +80,9 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -99,7 +108,7 @@ export {
required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { PageJsonLdOptions } from './modules/frontend/createContentHelpers.js'
export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
@@ -126,13 +135,18 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref, safeHref } from './modules/links/index.js'
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkAppearanceOption,
LinkValue,
NavItem,
ResolvedLink,
ResolveLinkHrefOptions,
ResolveNavOptions,
SystemLink,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
@@ -158,12 +172,14 @@ export {
SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG,
} from './modules/payload/index.js'
export { buildTableOfContentsField, extractHeadings, headingText } from './modules/richtext/headings.js'
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
@@ -200,20 +216,24 @@ export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler }
export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js'
export { buildSummaryField, SKIP_AUTO_FILL } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
export type { StatsOptions, StatsPage, StatsVisit } from './modules/stats/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js'
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, themeConfigFrom, themeScript } from './modules/theme/index.js'
export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'.
export { getTurnstileConfig } from './modules/turnstile/config.js'
+10 -6
View File
@@ -17,14 +17,18 @@ declare global {
const GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`
const GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`
/** Reads the current consent state from cookie, or defaults if none. */
function readConsent() {
/**
* Reads the current consent state from cookie, or defaults if none. `version`
* must be the panel's policy version — the same one useConsent checks — or a
* valid consent under any version other than 1 reads as "all denied".
*/
function readConsent(version: number | undefined) {
if (typeof document === 'undefined') {return DEFAULT_CONSENT}
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
return parseConsent(raw) ?? DEFAULT_CONSENT
return parseConsent(raw, version) ?? DEFAULT_CONSENT
}
function injectScript(src: string) {
@@ -121,7 +125,7 @@ export function Analytics(props: AnalyticsProps) {
} = props
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
const { state, texts } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
@@ -131,9 +135,9 @@ export function Analytics(props: AnalyticsProps) {
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
setDefaultConsent(readConsent())
setDefaultConsent(readConsent(texts.version))
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId])
}, [ga4MeasurementId, gtmContainerId, texts.version])
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(() => {
+2
View File
@@ -1,3 +1,5 @@
export { RenderBlocks } from './RenderBlocks.js'
export type { RenderBlocksProps } from './RenderBlocks.js'
export { buildSectionHeaderField, buildSectionSettingsField } from './sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './sectionFields.js'
export type { BlockComponentMap, BlockData, EnhanceProps } from './types.js'
+82
View File
@@ -0,0 +1,82 @@
import type { Field, GroupField } from 'payload'
/**
* The two field groups every section block shares — same panel, same data
* shape in every project, so the shared <Section>/<SectionHeader> components
* work on every block. Everything is overridable: names, options, extra fields.
*
* fields: [buildSectionHeaderField(), …the block's own fields…, buildSectionSettingsField()]
* fields: [buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }] })]
*/
export type SectionHeaderFieldOptions = {
/** Extra fields inside the group (e.g. a heading level select). */
fields?: Field[]
/** Generated TS type name. Default 'SectionHeaderData'. */
interfaceName?: string
/** Default 'header'. */
name?: string
}
/** eyebrow + heading + intro, localized — rendered by the project's <SectionHeader>. */
export function buildSectionHeaderField({ name = 'header', fields = [], interfaceName = 'SectionHeaderData' }: SectionHeaderFieldOptions = {}): GroupField {
return {
name,
type: 'group',
fields: [
{ name: 'eyebrow', type: 'text', admin: { description: 'Small line above the heading. Optional.' }, localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, localized: true },
...fields,
],
interfaceName,
}
}
export type SectionSettingsFieldOptions = {
/** Section #id for anchor links and a section nav. Default true. */
anchor?: boolean
/**
* Background choices — values map to the project's own classes in <Section>.
* Default Default / Muted / Inverted (dark). `false` → no background select.
*/
backgrounds?: { label: string; value: string }[] | false
/** Extra settings (e.g. spacing, width). */
fields?: Field[]
/** Generated TS type name. Default 'SectionSettings'. */
interfaceName?: string
/** Default 'settings'. */
name?: string
}
const DEFAULT_BACKGROUNDS = [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
]
/** Sidebar group: anchor + background (+ your own) — instead of bgColor / sectionId per block. */
export function buildSectionSettingsField({
name = 'settings',
anchor = true,
backgrounds = DEFAULT_BACKGROUNDS,
fields = [],
interfaceName = 'SectionSettings',
}: SectionSettingsFieldOptions = {}): GroupField {
return {
name,
type: 'group',
admin: { position: 'sidebar' },
fields: [
...(anchor
? [{ name: 'anchor', type: 'text', admin: { description: 'Section id for #links and section nav, e.g. "pricing".' } } as Field]
: []),
...(backgrounds && backgrounds.length
? [{ name: 'background', type: 'select', defaultValue: backgrounds[0].value, options: backgrounds } as Field]
: []),
...fields,
],
interfaceName,
label: 'Section settings',
}
}
+359 -79
View File
@@ -1,19 +1,90 @@
'use client'
import { Cookie } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
import { useIsMounted } from './useIsMounted.js'
/** A button on the banner (first level). */
export type CookieBannerAction = 'accept' | 'reject' | 'settings'
/** A button under the category list (settings view). */
export type CookieSettingsAction = 'accept' | 'back' | 'reject' | 'save'
/**
* Optional class overrides — for when tokens aren't enough, e.g. turning the
* bottom bar into a centred modal. Replaces the slot's classes outright.
* bottom bar into a centred modal. Each slot replaces its default classes
* outright. Per-button slots (acceptButton, rejectButton…) fall back to
* primaryButton / secondaryButton, so styling those two still restyles all.
*/
export type CookieBannerClassNames = {
/** Button "Accept all" — falls back to primaryButton. */
acceptButton?: string
/** Button row on the banner. */
actions?: string
/** Settings view: button "Back" (closes the dialog in modal mode) — falls back to secondaryButton. */
backButton?: string
/** Settings view: badge next to Necessary (CookieSettings → alwaysActiveLabel). */
badge?: string
/** Banner inner wrapper (width / centring). */
body?: string
/** Settings view: list of categories. */
categories?: string
/** Settings view: one category row/card. */
category?: string
/** Detailed window: the card around one category (row + cookie list). */
categoryCard?: string
categoryDescription?: string
categoryTitle?: string
/** Settings dialog (modal mode): the ✕ button. */
closeButton?: string
/** Banner: text + buttons row. */
content?: string
/** Settings view: the switch track or the checkbox. */
control?: string
/** Settings view: the switch knob (controls="switch"). */
controlThumb?: string
/** Detailed window: one cookie in a category's list. */
cookie?: string
/** Detailed window: list of cookies under a category. */
cookieList?: string
/** Detailed window: provider / purpose / duration grid of one cookie. */
cookieMeta?: string
/** Detailed window: cookie name. */
cookieName?: string
/** Detailed window: <details> wrapping a category's cookie list. */
cookies?: string
/** Detailed window: the <summary> that expands the cookie list. */
cookiesToggle?: string
/** Settings dialog box (modal mode; detailed mode uses a wider default). */
dialog?: string
/** Small label above the banner title (CookieSettings → eyebrow). */
eyebrow?: string
/** Cookie icon next to the banner text and the settings title. */
icon?: string
/** Privacy-policy link inside the message. */
link?: string
message?: string
/** Backdrop behind the settings dialog (modal mode). */
overlay?: string
primaryButton?: string
/** Button "Reject" — falls back to primaryButton with equalChoice, else secondaryButton. */
rejectButton?: string
root?: string
/** Settings view: button "Save preferences" — falls back to primaryButton. */
saveButton?: string
secondaryButton?: string
/** Settings view: button row under the categories. */
settingsActions?: string
/** Button "Settings" on the banner — falls back to secondaryButton. */
settingsButton?: string
/** Settings view: intro under the title (CookieSettings → settingsDescription). */
settingsDescription?: string
settingsTitle?: string
/** Banner: block with eyebrow, title and message. */
text?: string
/** Banner heading (CookieSettings → title). */
title?: string
}
/**
@@ -35,131 +106,340 @@ export type CookieBannerClassNames = {
*
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
* exposing them as tokens would mean re-inventing CSS one variable at a time.
* For a different layout use classNames (every element has a slot).
*/
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
const accent = 'text-[var(--ipal-primary,#2563eb)]'
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
const primaryBg = 'bg-[var(--ipal-primary,#2563eb)]'
const defaults = {
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
const defaults: Required<CookieBannerClassNames> = {
acceptButton: '',
actions: 'flex shrink-0 gap-2',
backButton: '',
badge: `shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${border} ${accent}`,
body: 'mx-auto max-w-4xl',
categories: 'flex flex-col gap-3',
category: 'flex items-start justify-between gap-4',
categoryCard: `flex flex-col gap-3 ${radius} border p-4 ${border}`,
categoryDescription: `text-xs ${mutedText}`,
categoryTitle: `text-sm font-medium ${strongText}`,
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,#f5f5f5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
cookie: `flex flex-col gap-1 border-t pt-2 first:border-t-0 first:pt-0 ${border}`,
cookieList: 'mt-3 flex flex-col gap-2',
cookieMeta: `grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs ${mutedText}`,
cookieName: `font-mono text-xs font-semibold ${strongText}`,
cookies: 'group',
cookiesToggle: `inline-flex cursor-pointer select-none items-center gap-1 text-xs font-medium ${accent} hover:underline [&::-webkit-details-marker]:hidden`,
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
icon: `h-6 w-6 shrink-0 ${accent}`,
link: `${accent} underline hover:no-underline`,
message: `text-justify text-sm ${bodyText}`,
overlay: 'fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4',
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium ${primaryBg} text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
rejectButton: '',
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
saveButton: '',
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
settingsActions: 'flex justify-end gap-2',
settingsButton: '',
settingsDescription: `text-sm ${bodyText}`,
settingsTitle: `flex items-center gap-2 text-base font-semibold ${strongText}`,
text: 'flex items-start gap-3',
title: `mb-1 text-base font-semibold ${strongText}`,
}
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
const strongText =
'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
/** Default switch track (controls="switch") — the checkbox default doesn't fit a <button>. */
/** Default dialog for settings="detailed" — wider and taller than the modal one. */
const DETAILED_DIALOG = `relative max-h-[90vh] w-full max-w-4xl overflow-y-auto ${radius} border p-6 shadow-2xl sm:p-8 ${surface} ${border}`
const SWITCH_TRACK =
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
type CookieBannerProps = {
classNames?: CookieBannerClassNames
/** Category controls: native checkboxes (default) or accessible switches (role="switch"). */
controls?: 'checkbox' | 'switch'
/**
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
* EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true.
*/
equalChoice?: boolean
/** Cookie icon next to the banner text and the settings title. Default true. */
icon?: boolean
/** Banner buttons, in this order. Default ['settings', 'reject', 'accept']. */
order?: CookieBannerAction[]
/**
* Where category settings open:
* - 'inline' (default) — in the banner itself;
* - 'modal' — a centred dialog over a dimmed page (closes with ✕, Escape or a click outside);
* - 'detailed' — like 'modal', but a large window: each category is a card with its
* on/off control, description and an expandable list of its cookies (name, provider,
* purpose, duration) from Cookie Settings → Cookies.
*/
settings?: 'detailed' | 'inline' | 'modal'
/** Buttons under the categories, in this order. Default ['back', 'save']. */
settingsActions?: CookieSettingsAction[]
}
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) {
const DEFAULT_ORDER: CookieBannerAction[] = ['settings', 'reject', 'accept']
const DEFAULT_SETTINGS_ACTIONS: CookieSettingsAction[] = ['back', 'save']
export function CookieBanner({
classNames,
controls = 'checkbox',
equalChoice = false,
icon = true,
order = DEFAULT_ORDER,
settings = 'inline',
settingsActions = DEFAULT_SETTINGS_ACTIONS,
}: CookieBannerProps = {}) {
const isMounted = useIsMounted()
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
const closeRef = useRef<HTMLButtonElement>(null)
const modal = settings !== 'inline'
const detailed = settings === 'detailed'
useEffect(() => {
setChoices(state)
}, [state])
// Modal: focus the ✕ on open, Escape closes (back to the banner)
useEffect(() => {
if (!modal || !showSettings) {return}
closeRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {setShowSettings(false)}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [modal, showSettings])
// Render nothing until mounted — avoids the React 19 hydration mismatch that
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now.
if (!isMounted) {return null}
if (decided) {return null}
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
const primary = cn('primaryButton')
const secondary = cn('secondaryButton')
const buttonClass: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: classNames?.acceptButton ?? primary,
back: classNames?.backButton ?? secondary,
reject: classNames?.rejectButton ?? (equalChoice ? primary : secondary),
save: classNames?.saveButton ?? primary,
settings: classNames?.settingsButton ?? secondary,
}
const run: Record<CookieBannerAction | CookieSettingsAction, () => void> = {
accept: acceptAll,
back: () => setShowSettings(false),
reject: rejectAll,
save: () => savePreferences(choices),
settings: () => setShowSettings(true),
}
const label: Record<CookieBannerAction | CookieSettingsAction, string> = {
accept: texts.buttons.acceptAll,
back: texts.buttons.back,
reject: texts.buttons.reject,
save: texts.buttons.save,
settings: texts.buttons.settings,
}
const button = (action: CookieBannerAction | CookieSettingsAction) => (
<button className={buttonClass[action]} data-ipal={action} key={action} onClick={run[action]} type="button">
{label[action]}
</button>
)
const toggle = (cat: ConsentCategory) => {
if (cat === 'necessary') {return}
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
}
const rootClass = classNames?.root ?? defaults.root
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton
const control = (cat: ConsentCategory) => {
const checked = cat === 'necessary' ? true : choices[cat]
if (cat === 'necessary' && texts.alwaysActiveLabel) {
return <span className={cn('badge')}>{texts.alwaysActiveLabel}</span>
}
if (controls === 'switch') {
return (
<button
aria-checked={checked}
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
className={classNames?.control ?? SWITCH_TRACK}
data-checked={checked}
disabled={cat === 'necessary'}
onClick={() => toggle(cat)}
role="switch"
type="button"
>
<span aria-hidden="true" className={cn('controlThumb')} data-checked={checked} />
</button>
)
}
return (
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={checked}
className={cn('control')}
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
)
}
return (
<div aria-label={texts.settingsTitle} className={rootClass} data-ipal="banner" role="dialog">
<div className="mx-auto max-w-4xl">
{!showSettings ? (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-start gap-3">
<Cookie aria-hidden="true" className={`h-6 w-6 shrink-0 ${accent}`} />
<p className={`text-justify text-sm ${bodyText}`}>
{texts.message}
{texts.privacyLink && (
const cookieList = (cat: ConsentCategory) => {
const rows = texts.cookies?.filter((row) => row.category === cat) ?? []
const labels = texts.details
if (!labels || rows.length === 0) {return null}
return (
<details className={cn('cookies')} data-ipal="cookies">
<summary className={cn('cookiesToggle')}>
<svg aria-hidden="true" className="transition-transform group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<path d="m9 18 6-6-6-6" />
</svg>
{labels.cookies} ({rows.length})
</summary>
<ul className={cn('cookieList')}>
{rows.map((row) => (
<li className={cn('cookie')} key={row.name}>
<code className={cn('cookieName')}>{row.name}</code>
<dl className={cn('cookieMeta')}>
{row.provider && (
<>
{' '}
<a
className={`${accent} underline hover:no-underline`}
href={texts.privacyLink.href}
>
{texts.privacyLink.label}
</a>
<dt>{labels.provider}</dt>
<dd>{row.provider}</dd>
</>
)}
</p>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings}
</button>
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject}
</button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
{texts.buttons.acceptAll}
</button>
{row.purpose && (
<>
<dt>{labels.purpose}</dt>
<dd>{row.purpose}</dd>
</>
)}
{row.duration && (
<>
<dt>{labels.duration}</dt>
<dd>{row.duration}</dd>
</>
)}
</dl>
</li>
))}
</ul>
</details>
)
}
const categoryRow = (cat: ConsentCategory) => (
<>
<div>
<p className={cn('categoryTitle')} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={cn('categoryDescription')} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
{control(cat)}
</>
)
const settingsView = (
<div className="flex flex-col gap-4">
<div className="flex items-start justify-between gap-4">
<h2 className={cn('settingsTitle')} id="ipal-consent-title">
{icon && (!modal || detailed) && <Cookie aria-hidden="true" className={cn('icon')} />}
{texts.settingsTitle}
</h2>
{modal && (
<button aria-label={texts.buttons.close} className={cn('closeButton')} data-ipal="close" onClick={() => setShowSettings(false)} ref={closeRef} type="button">
<svg aria-hidden="true" fill="none" height="20" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="20">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
)}
</div>
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
<ul className={cn('categories')}>
{CONSENT_CATEGORIES.map((cat) =>
detailed ? (
<li className={cn('categoryCard')} data-ipal={`category-${cat}`} key={cat}>
<div className={cn('category')}>{categoryRow(cat)}</div>
{cookieList(cat)}
</li>
) : (
<li className={cn('category')} key={cat}>
{categoryRow(cat)}
</li>
),
)}
</ul>
<div className={cn('settingsActions')}>{settingsActions.map(button)}</div>
</div>
)
if (modal && showSettings) {
return (
<div
className={cn('overlay')}
data-ipal="consent-overlay"
// banner text is not page content — keep it out of Google's snippets
data-nosnippet
onClick={(event) => {
if (event.target === event.currentTarget) {setShowSettings(false)}
}}
// klik w tło zamyka dialog; klawiatura: Escape (listener wyżej) i przycisk ✕
role="presentation"
>
<div aria-labelledby="ipal-consent-title" aria-modal="true" className={classNames?.dialog ?? (detailed ? DETAILED_DIALOG : defaults.dialog)} data-ipal="consent-dialog" role="dialog">
{settingsView}
</div>
</div>
)
}
return (
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet role="dialog">
<div className={cn('body')}>
{!showSettings ? (
<div className={cn('content')}>
<div className={cn('text')}>
{icon && <Cookie aria-hidden="true" className={cn('icon')} />}
<div>
{texts.eyebrow && <p className={cn('eyebrow')}>{texts.eyebrow}</p>}
{texts.title && <h2 className={cn('title')}>{texts.title}</h2>}
<p className={cn('message')}>
{texts.message}
{texts.privacyLink && (
<>
{' '}
<a className={cn('link')} href={texts.privacyLink.href}>
{texts.privacyLink.label}
</a>
</>
)}
</p>
</div>
</div>
<div className={cn('actions')}>{order.map(button)}</div>
</div>
) : (
<div className="flex flex-col gap-4">
<h2 className={`flex items-center gap-2 text-base font-semibold ${strongText}`}>
<Cookie aria-hidden="true" className={`h-5 w-5 ${accent}`} />
{texts.settingsTitle}
</h2>
<ul className="flex flex-col gap-3">
{CONSENT_CATEGORIES.map((cat) => (
<li className="flex items-start justify-between gap-4" key={cat}>
<div>
<p className={`text-sm font-medium ${strongText}`} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={`text-xs ${mutedText}`} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={cat === 'necessary' ? true : choices[cat]}
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
</li>
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)} type="button">
{texts.buttons.back}
</button>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)} type="button">
{texts.buttons.save}
</button>
</div>
</div>
settingsView
)}
</div>
</div>
+1 -1
View File
@@ -2,7 +2,7 @@
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js'
export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
+44 -18
View File
@@ -1,7 +1,7 @@
import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import type { ConsentTexts } from './texts.js'
import type { ConsentTexts, CookieTableRow } from './texts.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
import { getSystemPagePath } from '../pages/index.js'
@@ -13,6 +13,7 @@ const FALLBACK: ConsentTexts = {
buttons: {
acceptAll: 'Accept all',
back: 'Back',
close: 'Close',
reject: 'Reject',
save: 'Save preferences',
settings: 'Settings',
@@ -27,6 +28,7 @@ const FALLBACK: ConsentTexts = {
title: 'Necessary',
},
},
details: { cookies: 'Cookies used', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' },
message:
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.',
privacyLink: null,
@@ -37,13 +39,25 @@ const FALLBACK: ConsentTexts = {
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']>
alwaysActiveLabel?: null | string
buttons?: ({
/**
* Before 1.11.1 the field was `save` — still read for old MongoDB data. Not in the schema any
* more, so Payload doesn't flatten it: it comes back as the raw `{ pl, en }` map.
*/
save?: null | Record<string, string> | string
savePreferences?: null | string
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
detailLabels?: null | Partial<Record<keyof NonNullable<ConsentTexts['details']>, null | string>>
eyebrow?: null | string
message?: null | string
policyVersion?: null | number
privacyLinkLabel?: null | string
settingsDescription?: null | string
settingsTitle?: null | string
title?: null | string
}
type PrivacyPage = { slug?: null | Record<string, unknown>; title?: unknown } | null
@@ -135,24 +149,44 @@ export async function getConsentTexts({
buttons: {
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
back: g.buttons?.back || FALLBACK.buttons.back,
close: g.buttons?.close || FALLBACK.buttons.close,
reject: g.buttons?.reject || FALLBACK.buttons.reject,
save: g.buttons?.save || FALLBACK.buttons.save,
save: g.buttons?.savePreferences || resolveLocalized(g.buttons?.save, locale ?? '') || FALLBACK.buttons.save,
settings: g.buttons?.settings || FALLBACK.buttons.settings,
},
categories,
cookies: toCookieRows(g.cookies),
details: {
cookies: g.detailLabels?.cookies?.trim() || FALLBACK.details!.cookies,
duration: g.detailLabels?.duration?.trim() || FALLBACK.details!.duration,
provider: g.detailLabels?.provider?.trim() || FALLBACK.details!.provider,
purpose: g.detailLabels?.purpose?.trim() || FALLBACK.details!.purpose,
},
message: g.message || FALLBACK.message,
privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
// optional copy — no English fallback: empty in the panel = element not rendered
...(g.eyebrow?.trim() ? { eyebrow: g.eyebrow.trim() } : {}),
...(g.title?.trim() ? { title: g.title.trim() } : {}),
...(g.settingsDescription?.trim() ? { settingsDescription: g.settingsDescription.trim() } : {}),
...(g.alwaysActiveLabel?.trim() ? { alwaysActiveLabel: g.alwaysActiveLabel.trim() } : {}),
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
}
}
export type CookieTableRow = {
category: ConsentCategory
duration?: string
name: string
provider?: string
purpose?: string
export type { CookieTableRow } from './texts.js'
/** Named rows only; an unknown category falls back to necessary. */
function toCookieRows(cookies: CookieSettingsData['cookies']): CookieTableRow[] {
return (cookies ?? [])
.filter((c) => typeof c.name === 'string' && c.name.trim())
.map((c) => ({
name: c.name!.trim(),
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
}))
}
/**
@@ -162,15 +196,7 @@ export type CookieTableRow = {
export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise<CookieTableRow[]> {
try {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
return (g.cookies ?? [])
.filter((c) => typeof c.name === 'string' && c.name.trim())
.map((c) => ({
name: c.name!.trim(),
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
}))
return toCookieRows(g.cookies)
} catch {
return []
}
+33
View File
@@ -1,18 +1,51 @@
import type { ConsentCategory } from './categories.js'
export type ConsentTexts = {
/** Badge next to the necessary category (e.g. "Always active"). Empty = no badge. */
alwaysActiveLabel?: string
buttons: {
acceptAll: string
back: string
/** Accessible label of the ✕ button closing the settings dialog. */
close: string
reject: string
save: string
settings: string
}
categories: Record<ConsentCategory, { description: string; title: string }>
/**
* Cookie Settings → Cookies in this language — listed per category in the
* detailed settings window (<CookieBanner settings="detailed">). Optional so
* hand-built texts keep compiling; getConsentTexts always fills it.
*/
cookies?: CookieTableRow[]
/** Labels of the cookie list in the detailed settings window. No labels = no list. */
details?: {
/** Expander per category, e.g. "Cookies used" — the count is appended. */
cookies: string
duration: string
provider: string
purpose: string
}
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
eyebrow?: string
message: string
/** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null
/** Intro under the settings title. Empty = not shown. */
settingsDescription?: string
settingsTitle: string
/** Banner heading (e.g. "We respect your privacy"). Empty = not shown. */
title?: string
/** Policy version from the panel — a stored consent from another version asks again. */
version?: number
}
/** One row of Cookie Settings → Cookies, resolved to a single language. */
export type CookieTableRow = {
category: ConsentCategory
duration?: string
name: string
provider?: string
purpose?: string
}
+1 -1
View File
@@ -17,7 +17,7 @@ export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
* projects add theirs through <ConsentProvider cookieMap> (merged, not replaced).
*/
export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'],
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*', 'ipal_vid'],
functional: [LOCALE_COOKIE_NAME],
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
}
@@ -0,0 +1,85 @@
'use client'
import { useCallback, useEffect, useId, useRef, useState } from 'react'
import type { ConstructionMode } from './types.js'
import { isPathAllowed } from './logic.js'
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
export type ConstructionNoticeClassNames = {
button?: string
dialog?: string
message?: string
overlay?: string
title?: string
}
/**
* The "site under construction" notice (Site Settings → Under construction).
* Opens after a redirect from a blocked address (?notice=construction, then
* removed from the URL) and when a visitor clicks a link to a page that isn't
* available — the click is cancelled. Closes with its button or Escape.
* Renders nothing while the mode is off.
*
* Unstyled (classNames, like CookieBanner); texts come from the panel.
*
* // [locale]/layout.tsx
* <ConstructionNotice mode={await getConstructionMode(locale)} classNames={{ overlay: '…', dialog: '…' }} />
*/
export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) {
const [open, setOpen] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const titleId = useId()
const close = useCallback(() => setOpen(false), [])
const { allowedPaths, enabled } = mode
useEffect(() => {
if (!enabled) {return}
// After a redirect: show the notice once and clean the address bar
const url = new URL(window.location.href)
if (url.searchParams.get(CONSTRUCTION_NOTICE_PARAM) === CONSTRUCTION_NOTICE_VALUE) {
setOpen(true)
url.searchParams.delete(CONSTRUCTION_NOTICE_PARAM)
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`)
}
// Capture phase, before Next's <Link> — a cancelled click doesn't navigate
const onClick = (event: MouseEvent) => {
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {return}
const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute('download')) {return}
if (anchor.target && anchor.target !== '_self') {return}
const target = new URL(anchor.href, window.location.href)
if (target.origin !== window.location.origin || isPathAllowed(target.pathname, allowedPaths)) {return}
event.preventDefault()
event.stopPropagation()
setOpen(true)
}
document.addEventListener('click', onClick, true)
return () => document.removeEventListener('click', onClick, true)
}, [enabled, allowedPaths])
useEffect(() => {
if (!open) {return}
buttonRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {close()}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open, close])
if (!enabled || !open) {return null}
return (
<div className={cn.overlay} data-ipal="construction-notice">
<div aria-labelledby={mode.texts.title ? titleId : undefined} aria-modal="true" className={cn.dialog} role="dialog">
{mode.texts.title ? <p className={cn.title} id={titleId}>{mode.texts.title}</p> : null}
{mode.texts.message ? <p className={cn.message}>{mode.texts.message}</p> : null}
<button className={cn.button} onClick={close} ref={buttonRef} type="button">
{mode.texts.button ?? '×'}
</button>
</div>
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import type { Field } from 'payload'
const whenEnabled = (_: unknown, siblingData: { enabled?: boolean } | undefined) => Boolean(siblingData?.enabled)
/**
* Site Settings → "Under construction" tab: a developer tool for a site that
* isn't finished. When enabled, only the homepage and the chosen pages are
* reachable — any other address redirects to the homepage with a notice, and a
* link to another page shows the notice instead of navigating. One rule for
* every visitor (pages stay static, there is no per-user check).
*/
export function buildConstructionFields(pagesSlug: string): Field[] {
return [
{
name: 'construction',
type: 'group',
admin: { hideGutter: true },
fields: [
{
name: 'enabled',
type: 'checkbox',
admin: {
description:
'Only the homepage and the pages below can be opened. Other addresses redirect to the homepage with the notice; links to other pages show it instead of navigating.',
},
defaultValue: false,
label: 'Site under construction',
},
{
name: 'allowedPages',
type: 'relationship',
admin: { condition: whenEnabled, description: 'The homepage is always available.' },
hasMany: true,
label: 'Pages still available',
relationTo: pagesSlug as never,
},
{ name: 'title', type: 'text', admin: { condition: whenEnabled }, label: 'Notice title', localized: true },
{ name: 'message', type: 'textarea', admin: { condition: whenEnabled }, label: 'Notice text', localized: true },
{ name: 'buttonLabel', type: 'text', admin: { condition: whenEnabled }, label: 'Close button label', localized: true },
],
label: false,
},
]
}
+17
View File
@@ -0,0 +1,17 @@
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
/** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */
export const normalizePath = (path: string): string => {
const trimmed = path.replace(/\/+$/, '')
return trimmed === '' ? '/' : trimmed
}
/** Is this pathname one of the allowed ones? Exact match, trailing slash ignored. */
export function isPathAllowed(pathname: string, allowedPaths: readonly string[]): boolean {
const path = normalizePath(pathname)
return allowedPaths.some((allowed) => normalizePath(allowed) === path)
}
/** Where a blocked address goes: the homepage with the notice parameter. */
export const constructionNoticeHref = (homePath: string): string =>
`${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}`
+17
View File
@@ -0,0 +1,17 @@
/**
* "Site under construction" (Site Settings → Under construction) as the
* frontend needs it: getConstructionMode(locale) in createContentHelpers.
*/
export type ConstructionMode = {
/** Paths a visitor may open, in every language: the homepage and "Pages still available". */
allowedPaths: string[]
enabled: boolean
/** Homepage in the current language — blocked addresses redirect here (with the notice). */
homePath: string
/** Notice texts from the panel, in the current language. Empty = not set. */
texts: { button?: string; message?: string; title?: string }
}
/** Query parameter that opens the notice after a redirect: /pl?notice=construction */
export const CONSTRUCTION_NOTICE_PARAM = 'notice'
export const CONSTRUCTION_NOTICE_VALUE = 'construction'
+22 -3
View File
@@ -17,7 +17,7 @@ type CreateMarkdownRendererArgs = {
* i18n config — only to know a single-locale site has no /{locale} prefix in
* its URLs (for `url:`). Omit on multilingual sites if you like.
*/
config?: { locales: readonly unknown[] }
config?: { defaultLocale?: string; locales: readonly unknown[] }
/** Archive-backed collections, same value as the plugin option (optional). */
content?: ContentOption
/** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
@@ -149,7 +149,26 @@ function canonicalOf(baseUrl: string | undefined, config: { locales: readonly un
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
}
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> }
type MarkdownRouteContext = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* Locale + slug of a Markdown request. Multilingual: app/md/[locale]/[[...slug]].
* Single language (no /pl in URLs): app/md/[[...slug]] — no locale param, the
* only locale is used; the [locale] route also works there for subpages
* ("/md/kontakt" arrives as locale "kontakt" and is read as the slug).
*/
function routeOf(
params: { locale?: string; slug?: string[] },
config: CreateMarkdownRendererArgs['config'],
): { locale: string; slug?: string[] } {
const codes = (config?.locales ?? []).map((l) => (l && typeof l === 'object' ? (l as { code?: string }).code ?? '' : typeof l === 'string' ? l : ''))
const fallback = config?.defaultLocale ?? codes[0] ?? ''
if (!params.locale) {return { slug: params.slug, locale: fallback }}
if (codes.length === 1 && !codes.includes(params.locale)) {
return { slug: [params.locale, ...(params.slug ?? [])], locale: codes[0] }
}
return { slug: params.slug, locale: params.locale }
}
/**
* The whole Markdown route in one call — same options as createMarkdownRenderer
@@ -175,7 +194,7 @@ export function createMarkdownRoute(
return {
GET: async (_req, { params }) => {
try {
const { slug, locale } = await params
const { slug, locale } = routeOf(await params, rendererArgs.config)
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
+16 -5
View File
@@ -16,7 +16,12 @@ export type IpalEnvFeatures = {
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
serverUrlVar?: string
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
/**
* R2 object storage (buildR2Storage). Adds the R2_* vars — required in
* production (media on a container disk vanish on redeploy). Outside
* production they're optional (media go to the local disk), but a partial
* set is an error: buildR2Storage needs all of them.
*/
storage?: boolean
/**
* Cloudflare Turnstile. true uses the common var names
@@ -69,14 +74,20 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
]
if (storage) {
const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT']
// Production: always. Development: once any credential is set (all or nothing).
// R2_PUBLIC_URL alone is the read-only media mode (buildR2Storage) — allowed in dev.
const r2Required =
process.env.NODE_ENV === 'production' || r2Credentials.some((name) => Boolean(process.env[name]))
rules.push(
{ name: 'R2_BUCKET', description: 'R2 bucket name' },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },
{ name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
{
name: 'R2_PUBLIC_URL',
description: 'Public base URL media is served from (custom domain of the bucket)',
required: r2Required,
// Production: absolute URL (https://media.example.com). Outside production a
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
+237
View File
@@ -0,0 +1,237 @@
'use client'
import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
import { honeypotInputProps } from './honeypot.js'
import { useBuilderForm } from './useBuilderForm.js'
/**
* Class names for every element — the plugin ships none. Set them once in the
* project (e.g. src/components/forms/formClasses.ts) and every panel form looks
* the same. Plain strings, so a server component can pass them.
*/
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
>
>
export type BuilderFieldRenderArgs = {
/** The default markup for this field — return it to keep it, or wrap it. */
defaultRender: () => ReactNode
field: BuilderField
form: BuilderFormApi
/** Position in the panel's field list (key of `messages`). */
index: number
}
export type BuilderFormProps = {
classNames?: BuilderFormClassNames
/** Shown after success instead of the form (the form's confirmation message, rendered by RenderForm). */
confirmation?: ReactNode
/** Rendered `message` blocks, keyed by their index in form.fields (RenderForm fills it). */
messages?: Record<number, ReactNode>
/**
* Client-side only (use BuilderForm from a 'use client' file): replace the
* markup of chosen fields — a project's own field type, option cards, a
* slider. Return undefined to keep the default.
*/
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
} & UseBuilderFormOptions
/** A page-supplied value (always a string from `values`) as text. */
const fixedText = (value: unknown) => (typeof value === 'string' ? value : '')
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/**
* Renders ANY panel form — single screen or step-by-step, text, e-mail, number,
* date, select, radio, checkbox, checkbox group, message blocks — with plain,
* accessible HTML and no styles. Look: `classNames` (+ `data-*` hooks:
* data-ipal="form", data-type, data-width, data-step). Different markup:
* `renderField`, or your own component on useBuilderForm.
*
* In a block, use RenderForm (/rsc) — it renders the rich text, binds the
* action and passes only the public part of the form to the browser.
*/
export function BuilderForm({
classNames: cn = {},
confirmation,
messages = {},
renderField,
requiredMark,
turnstileTheme,
...options
}: BuilderFormProps) {
const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null)
const prevStep = useRef(f.stepIndex)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
// Compare with the previous step, not a "first render" flag: React re-runs effects
// without a remount (Next restoring a visited page from <Activity>, StrictMode),
// and a stale flag would focus the first field and scroll the page to the form.
useEffect(() => {
if (prevStep.current === f.stepIndex) {return}
prevStep.current = f.stepIndex
const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus()
}, [f.stepIndex])
if (f.isSuccess && options.form.confirmationType !== 'redirect') {
return (
<div className={cn.success} data-ipal="form-success" role="status">
{confirmation ?? f.resultMessage ?? options.texts.success}
</div>
)
}
const label = (field: BuilderField) => (
<>
{field.label}
{field.required && requiredMark ? <span aria-hidden className={cn.required}>{requiredMark}</span> : null}
</>
)
const errorOf = (field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return error ? <p className={cn.error} id={f.errorId(field)}>{error}</p> : null
}
const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
if (f.isFixed(field)) {
// Filled by the page (`values`): visible, not editable, sent with the form.
const id = f.fieldId(field)
return (
<>
<span className={cn.label} id={`${id}-label`}>{field.label}</span>
<output aria-labelledby={`${id}-label`} className={cn.fixed} data-ipal="form-fixed" id={id}>
{fixedText(f.values[field.name ?? ''])}
</output>
</>
)
}
switch (field.blockType) {
case 'checkbox': {
const props = f.getInputProps(field)
return (
<>
<label className={cn.checkboxLabel} htmlFor={props.id}>
<input {...props} className={cn.checkbox} />
<span>{label(field)}</span>
</label>
{errorOf(field)}
</>
)
}
case 'checkboxGroup':
case 'radio':
return (
<fieldset
aria-describedby={f.getFieldProps(field)['aria-describedby']}
aria-invalid={f.getFieldProps(field)['aria-invalid']}
className={cn.choices}
id={f.fieldId(field)}
>
<legend className={cn.legend}>{label(field)}</legend>
{(field.options ?? []).map((option, i) => {
const o = f.getOptionProps(field, option, i)
return (
<label className={cn.choice} htmlFor={o.id} key={option.value}>
<input {...o} className={cn.choiceInput} />
<span className={cn.choiceLabel}>{option.label ?? option.value}</span>
</label>
)
})}
{errorOf(field)}
</fieldset>
)
case 'select': {
const props = f.getSelectProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<select {...props} className={cn.select}>
<option value="">{field.placeholder ?? ''}</option>
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
{errorOf(field)}
</>
)
}
case 'textarea': {
const props = f.getTextareaProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<textarea {...props} className={cn.textarea} rows={5} />
{errorOf(field)}
</>
)
}
default: {
const props = f.getInputProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<input {...props} className={cn.input} />
{errorOf(field)}
</>
)
}
}
}
const { step } = f
const progress = options.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))
return (
<form className={cn.form} data-ipal="form" data-step={f.stepIndex + 1} noValidate onSubmit={f.submit}>
<input {...honeypotInputProps()} />
{f.total > 1 && progress ? <p aria-live="polite" className={cn.progress}>{progress}</p> : null}
<div className={cn.step} data-ipal="form-step" ref={stepRef} tabIndex={-1}>
{step.title ? <p className={cn.stepTitle}>{step.title}</p> : null}
{step.description ? <p className={cn.stepDescription}>{step.description}</p> : null}
<div className={cn.fields}>
{step.fields.map(({ field, index }) => {
const half = typeof field.width === 'number' && field.width <= 50
const content = renderField?.({ defaultRender: () => defaultField(field, index), field, form: f, index }) ?? defaultField(field, index)
return (
<div
className={cx(cn.field, half ? cn.fieldHalf : cn.fieldFull)}
data-type={field.blockType}
data-width={field.width ?? 100}
key={field.id ?? `${field.blockType}-${index}`}
>
{content}
</div>
)
})}
</div>
</div>
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
<div className={cn.actions}>
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
<button className={f.isLast ? cn.submit : (cn.next ?? cn.submit)} disabled={f.isSubmitting} type="submit">
{f.isLast ? options.form.submitButtonLabel || 'Send' : options.texts.next ?? 'Next'}
</button>
</div>
</form>
)
}
+162
View File
@@ -0,0 +1,162 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
import { RenderRichText } from '../richtext/RenderRichText.js'
import { BuilderForm } from './BuilderForm.js'
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
export type SendFormAction = (
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<SubmitActionResult>
export type RenderFormProps = {
/** The project's `sendForm` server action (createSubmitAction). */
action: SendFormAction
classNames?: BuilderFormClassNames
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
form: BuilderFormDoc | null | number | string | undefined
/**
* For redirect forms pointing at a page: `{ config: i18nConfig, homeSlug }`
* (locale is added). Without it only a custom URL redirect works.
*/
linkOptions?: Omit<ResolveLinkHrefOptions, 'locale'>
locale: string
requiredMark?: ReactNode
richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
/** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */
values?: Record<string, string>
}
/** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */
export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return {
id: form.id,
analytics: form.analytics,
confirmationType: form.confirmationType,
fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field),
redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null,
submitButtonLabel: form.submitButtonLabel,
title: form.title,
}
}
export type PrepareBuilderFormArgs = Pick<
RenderFormProps,
'action' | 'converters' | 'form' | 'linkOptions' | 'locale' | 'richTextClassName'
>
/** What the browser gets for a panel form — spread it into <BuilderForm> (plus texts, classNames, values). */
export type PreparedBuilderForm = {
action: (values: Record<string, unknown>, turnstileToken?: string) => Promise<SubmitActionResult>
confirmation: ReactNode
form: BuilderFormDoc
messages: Record<number, ReactNode>
redirectHref: null | string
}
/**
* The server half of RenderForm without the markup: the public part of the form,
* rendered message blocks and confirmation, the action bound to form + locale,
* the redirect target. For a client component that renders <BuilderForm> itself —
* e.g. with `values` that change in the browser (a product configurator):
*
* // server
* const prepared = prepareBuilderForm({ form, action: sendForm, locale })
* <ProductConfigurator form={prepared} texts={formTexts} />
* // client
* <BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
*
* Returns null for an unpopulated form (an id or nothing).
*/
export function prepareBuilderForm({
action,
converters,
form,
linkOptions,
locale,
richTextClassName,
}: PrepareBuilderFormArgs): null | PreparedBuilderForm {
if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) =>
data ? <RenderRichText className={richTextClassName} converters={converters} data={data as SerializedEditorState} /> : null
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((field, i) => {
if (field.blockType === 'message' && field.message) {messages[i] = rich(field.message)}
})
const page = form.redirect?.type === 'reference' ? (form.redirect.reference as { value?: unknown } | null)?.value : undefined
const redirectHref =
form.confirmationType === 'redirect'
? page && linkOptions
? resolveLinkHref({ type: 'internal', page }, { ...linkOptions, locale })
: safeHref(form.redirect?.url)
: null
return {
action: action.bind(null, String(form.id), locale),
confirmation: rich(form.confirmationMessage),
form: publicForm(form),
messages,
redirectHref,
}
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
*
* `values` fill fields the page already knows (`{ subject: 'Brooches' }`): shown
* read-only and sent with the submission. Values that change in the browser:
* prepareBuilderForm + <BuilderForm values>.
*/
export function RenderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
values,
}: RenderFormProps) {
const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName })
if (!prepared) {return null}
return (
<BuilderForm
{...prepared}
classNames={classNames}
requiredMark={requiredMark}
texts={texts}
turnstileTheme={turnstileTheme}
values={values}
/>
)
}
+142
View File
@@ -0,0 +1,142 @@
import type { Block, Field } from 'payload'
/**
* Extra form-builder field types — what the built-in set can't express:
*
* - `step` — a divider: fields below it (until the next Step) are one
* screen of a step-by-step form, with Next / Back buttons.
* Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[].
* - `time` — a time of day (<input type="time">). Value: "HH:MM".
*
* Built-in text · email · textarea · number get a localized "Placeholder"
* (withPlaceholder) — the hint inside the empty field, e.g. "e.g. 10:00–12:00".
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
* (`showWhen`) — conditional visibility, evaluated by visibleFields.
*/
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
required: true,
}
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
/**
* "Show only when": the field — or, on a Step, the whole step — appears only
* when another field has one of the given values. Evaluated by visibleFields
* in the browser and again on the server (hidden fields are neither required nor stored).
*/
export const showWhenField: Field = {
name: 'showWhen',
type: 'group',
admin: {
description:
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
},
fields: [
{
type: 'row',
fields: [
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
{
name: 'values',
type: 'text',
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
label: 'Values',
},
],
},
],
label: 'Show only when',
}
/** Adds "Show only when" at the end of a block's fields. */
export function withShowWhen<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, showWhenField] }
}
/** Hint inside the empty field. Localized — it is visible text. */
export const placeholderField: Field = {
name: 'placeholder',
type: 'text',
admin: { description: 'Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.' },
label: 'Placeholder',
localized: true,
}
/** Adds a localized "Placeholder" to a block (built-in text, email, textarea, number). */
export function withPlaceholder<B extends Block>(block: B): B {
return { ...block, fields: [...block.fields, placeholderField] }
}
const timeBase: Block = {
slug: 'time',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
],
labels: { plural: 'Times', singular: 'Time' },
}
const stepBase: Block = {
slug: 'step',
fields: [
{
name: 'title',
type: 'text',
admin: {
description:
'Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.',
},
label: 'Step title',
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
}
const checkboxGroupBase: Block = {
slug: 'checkboxGroup',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
{
name: 'options',
type: 'array',
fields: [
{
type: 'row',
fields: [
{ name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: 'Value', required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
minRows: 1,
},
{
type: 'row',
fields: [
{ name: 'minSelected', type: 'number', admin: { description: 'Empty = no minimum (Required = at least one).', width: '50%' }, label: 'Minimum selected', min: 0 },
{ name: 'maxSelected', type: 'number', admin: { description: 'Empty = no limit.', width: '50%' }, label: 'Maximum selected', min: 1 },
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
}
export const stepBlock: Block = withShowWhen(stepBase)
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
export const timeBlock: Block = withShowWhen(timeBase)
+157
View File
@@ -0,0 +1,157 @@
import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js'
/**
* Pure logic of a panel form — steps, initial values, validation. No React, so
* it's shared by useBuilderForm and tested on its own. The server re-checks
* everything (validateSubmission); this is only for instant feedback.
*/
/** Fields that hold a value (have a name and aren't message/step). */
export function inputFields(fields: BuilderField[] | null | undefined): ({ name: string } & BuilderField)[] {
return (fields ?? []).filter(
(f): f is { name: string } & BuilderField => typeof f.name === 'string' && f.name !== '' && !NON_INPUT_TYPES.has(f.blockType),
)
}
/**
* Splits the field list at `step` blocks. Fields before the first Step form
* the first screen; a form without Steps is one screen.
*
* `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a
* hidden Step with everything under it — out, while `index` stays the field's
* position in the full list (RenderForm renders `message` blocks by it).
*/
export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] {
const steps: BuilderStep[] = []
let current: BuilderStep | null = null
let skipping = false
;(fields ?? []).forEach((field, index) => {
if (field.blockType === 'step') {
skipping = isShown ? !isShown(field) : false
if (skipping) {return}
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
steps.push(current)
return
}
if (skipping || (isShown && !isShown(field))) {return}
if (!current) {
current = { fields: [], index: 0 }
steps.push(current)
}
current.fields.push({ field, index })
})
// Drop screens a trailing / doubled Step left empty.
const kept = steps.filter((s) => s.fields.length > 0)
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
}
const isBlankValue = (v: unknown) =>
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */
type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null }
const conditionValues = (condition: FieldCondition | null | undefined) =>
(condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean)
/**
* The fields (Steps and messages included) a visitor sees for the given values,
* in panel order. A field is hidden when its own "Show only when" fails, when
* its Step's condition fails (the whole step goes), or when the field its
* condition points at is itself hidden. A condition naming a field that doesn't
* exist hides the field — a typo shows up in the preview instead of passing silently.
*
* Shared by the browser (useBuilderForm: which steps and fields to show and
* validate) and the server (validateSubmission: hidden fields are neither
* required nor stored), so both agree on what was on screen.
*/
export function visibleFields<F extends ConditionalField>(fields: F[] | null | undefined, values: Record<string, unknown>): F[] {
const list = fields ?? []
const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f]))
const stepOf = new Map<F, F | undefined>()
let currentStep: F | undefined
for (const field of list) {
if (field.blockType === 'step') {currentStep = field}
stepOf.set(field, field.blockType === 'step' ? undefined : currentStep)
}
const cache = new Map<F, boolean>()
const met = (condition: FieldCondition | null | undefined, seen: Set<F>): boolean => {
const ref = condition?.field?.trim()
if (!ref) {return true}
const target = byName.get(ref)
if (!target || seen.has(target) || !visible(target, seen)) {return false}
const value = values[ref]
const wanted = conditionValues(condition)
if (wanted.length === 0) {return !isBlankValue(value)}
if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))}
return value != null && value !== '' && wanted.includes(String(value as boolean | number | string))
}
const visible = (field: F, seen: Set<F> = new Set()): boolean => {
const cached = cache.get(field)
if (cached !== undefined) {return cached}
const nextSeen = new Set(seen).add(field)
const step = stepOf.get(field)
const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen)
cache.set(field, result)
return result
}
return list.filter((field) => visible(field))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries(
inputFields(fields).map((f) => {
if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]}
if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]}
const v = f.defaultValue
return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : '']
}),
)
}
const isBlank = isBlankValue
/** Errors for the given fields (one message per field), empty object = valid. */
export function validateBuilderFields(
fields: BuilderField[],
values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'validation'>,
): Record<string, string> {
const errors: Record<string, string> = {}
for (const f of inputFields(fields)) {
const v = values[f.name]
const msg = texts.validation.replace('{field}', f.label || f.name)
if (isBlank(v)) {
if (f.required) {errors[f.name] = msg}
continue
}
if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg}
else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) {
if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg}
}
}
return errors
}
/** Index of the step holding a field — to jump back to it after a failed submit. */
export function stepOfField(steps: BuilderStep[], name: string): number {
const i = steps.findIndex((s) => s.fields.some(({ field }) => field.name === name))
return i < 0 ? 0 : i
}
/** Browser autofill hint from the field type / a conventional name. */
export function autoCompleteFor(field: BuilderField): string | undefined {
if (field.blockType === 'email') {return 'email'}
if (field.blockType === 'country') {return 'country-name'}
const n = (field.name ?? '').toLowerCase()
if (/^(?:full_?)?name$|^imie/.test(n)) {return 'name'}
if (/phone|tel/.test(n)) {return 'tel'}
if (/company|organi[sz]ation|firma/.test(n)) {return 'organization'}
return undefined
}
+78
View File
@@ -0,0 +1,78 @@
import type { FormAnalyticsConfig } from './formAnalytics.js'
/**
* Shapes of a panel form as the frontend receives it (form-builder + ipal's
* step / checkboxGroup). Loose on purpose — the project's generated types fit.
*/
export type BuilderOption = { label?: null | string; value: string }
/**
* "Show only when" of a field or a Step (panel group `showWhen`): visible only
* when the field named `field` has one of `values` (comma-separated). Empty
* `values` = when that field is filled in / ticked. Empty `field` = always.
*/
export type FieldCondition = { field?: null | string; values?: null | string }
export type BuilderField = {
blockName?: null | string
/** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
description?: null | string
id?: null | string
label?: null | string
maxSelected?: null | number
/** message — rich text, rendered on the server (RenderForm) */
message?: unknown
minSelected?: null | number
name?: null | string
options?: BuilderOption[] | null
placeholder?: null | string
required?: boolean | null
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
showWhen?: FieldCondition | null
/** step */
title?: null | string
width?: null | number
}
export type BuilderFormDoc = {
analytics?: FormAnalyticsConfig
confirmationMessage?: unknown
confirmationType?: 'message' | 'redirect' | null
fields?: BuilderField[] | null
id: number | string
redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null
submitButtonLabel?: null | string
title?: null | string
}
/** Texts the form needs — Notifications → form (getNotificationTexts) fits. */
export type BuilderFormTexts = {
back?: string
error?: string
next?: string
/** "Step {current} of {total}" */
stepOf?: string
success?: string
/** "Please check the {field} field" */
validation: string
}
/** The bound server action: createSubmitAction(...) bound to formId + locale (RenderForm does it). */
export type BuilderFormAction = (
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<{ field?: string; message?: string; reason?: string; success: boolean }>
export type BuilderStep = {
description?: string
/** Every field of the step, `message` blocks included, in panel order. */
fields: { field: BuilderField; index: number }[]
index: number
title?: string
}
/** Field types that carry no value. */
export const NON_INPUT_TYPES = new Set(['message', 'step'])
+1
View File
@@ -75,6 +75,7 @@ export function createSubmitAction({
data: fields,
formId: String(formId),
ip,
locale,
maxPerMinute,
payload,
turnstileOnConfigError,
+188
View File
@@ -0,0 +1,188 @@
import type { FormattedEmail } from '@payloadcms/plugin-form-builder/types'
import type { Field, PayloadRequest } from 'payload'
import type { BuilderField } from './builderTypes.js'
/**
* Branded e-mails for panel forms (`forms: { emailLayout: true }`).
*
* The form-builder sends what the editor wrote in Forms → Emails, with
* `{{*:table}}` rendered as a bare `field : value` table — technical names
* (`web_type`) and raw option values (`redesign_site`). This module swaps that
* table for a readable summary (the question as the visitor saw it, option
* labels, grouped by step, blanks left out) and wraps the message in an
* e-mail-safe layout (tables + inline CSS) with the logo, accent colour and
* footer from Site Settings → Emails. Pure functions + one beforeEmail hook.
*/
export type SummaryRow = { label: string; value: string }
export type SummaryGroup = { rows: SummaryRow[]; title?: string }
type SubmissionValue = { field?: null | string; value?: unknown }
const NON_INPUT = new Set(['message', 'step'])
const escapeHtml = (text: string): string =>
text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
const asText = (value: unknown): string =>
value == null ? '' : typeof value === 'string' ? value : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value)
/**
* The stored submission as readable rows: one group per Step (titled), the
* field label as the question, option labels instead of values (a checkbox
* group's "a, b" too), a ticked checkbox as ✓. Empty answers are skipped.
*/
export function buildSubmissionSummary(fields: BuilderField[] | null | undefined, submissionData: readonly SubmissionValue[]): SummaryGroup[] {
const stored = new Map(submissionData.filter((d) => d.field).map((d) => [d.field as string, asText(d.value).trim()]))
const groups: SummaryGroup[] = [{ rows: [] }]
for (const field of fields ?? []) {
if (field.blockType === 'step') {
groups.push({ rows: [], ...(field.title ? { title: field.title } : {}) })
continue
}
if (!field.name || NON_INPUT.has(field.blockType)) {continue}
const raw = stored.get(field.name)
if (!raw || raw === 'false') {continue}
const optionLabel = (value: string) => field.options?.find((o) => o.value === value)?.label || value
const value =
field.blockType === 'checkbox' ? '✓'
: field.blockType === 'checkboxGroup' ? raw.split(', ').map(optionLabel).join(', ')
: field.options?.length ? optionLabel(raw)
: raw
groups[groups.length - 1].rows.push({ label: field.label || field.name, value })
}
return groups.filter((g) => g.rows.length > 0)
}
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
/** The summary as an e-mail-safe table (inline CSS only). */
export function renderSummaryHtml(groups: SummaryGroup[], { accent }: { accent: string }): string {
const rows = groups
.map((group) => {
const title = group.title
? `<tr><td colspan="2" class="ipal-group" style="padding:22px 0 8px;font-family:${FONT};font-size:13px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;color:${accent};border-bottom:2px solid ${accent};">${escapeHtml(group.title)}</td></tr>`
: ''
const items = group.rows
.map(
(row) =>
`<tr class="ipal-row"><td valign="top" class="ipal-label" style="padding:10px 16px 10px 0;width:42%;font-family:${FONT};font-size:13px;line-height:1.5;color:#6b7280;border-bottom:1px solid #eceef1;">${escapeHtml(row.label)}</td>` +
`<td valign="top" class="ipal-value" style="padding:10px 0;font-family:${FONT};font-size:14px;line-height:1.5;color:#111827;border-bottom:1px solid #eceef1;white-space:pre-line;">${escapeHtml(row.value)}</td></tr>`,
)
.join('')
return title + items
})
.join('')
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin:8px 0 4px;">${rows}</table>`
}
/** form-builder's `{{*:table}}` output (optionally inside a paragraph) → the readable summary. */
export const replaceSubmissionTable = (html: string, summaryHtml: string): string =>
html.replace(/(<p[^>]*>\s*)?<table>[\s\S]*?<\/table>(\s*<\/p>)?/g, summaryHtml)
export type EmailLayoutArgs = {
/** Accent colour (hex), Site Settings → Emails. */
accent: string
/** The message body (HTML from the panel, summary already in). */
content: string
/** Footer line, Site Settings → Emails. */
footer?: string
/** Absolute URL of a PNG/JPG logo — without it the site name is shown. */
logoUrl?: string
siteName?: string
siteUrl?: string
}
/** A complete HTML e-mail: header (logo or name), the message, footer. Tables + inline CSS. */
export function wrapEmailHtml({ accent, content, footer, logoUrl, siteName, siteUrl }: EmailLayoutArgs): string {
const name = siteName ? escapeHtml(siteName) : ''
const brand = logoUrl
? `<img src="${escapeHtml(logoUrl)}" alt="${name}" height="36" style="display:block;height:36px;width:auto;border:0;">`
: `<span style="font-family:${FONT};font-size:20px;font-weight:700;color:#111827;">${name}</span>`
const linkedBrand = siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="text-decoration:none;">${brand}</a>` : brand
const footerLines = [footer ? escapeHtml(footer).replace(/\n/g, '<br>') : '', siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="color:#6b7280;">${escapeHtml(siteUrl.replace(/^https?:\/\//, ''))}</a>` : '']
.filter(Boolean)
.join('<br>')
return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light">
<style>@media (max-width:520px){.ipal-pad{padding-left:20px!important;padding-right:20px!important}.ipal-row td{display:block!important;width:auto!important}.ipal-label{padding:12px 0 2px!important;border-bottom:0!important}.ipal-value{padding:0 0 12px!important}}</style></head>
<body style="margin:0;padding:0;background:#f3f4f6;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f3f4f6;"><tr><td align="center" style="padding:32px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:#ffffff;border-radius:12px;overflow:hidden;border-top:4px solid ${accent};">
<tr><td class="ipal-pad" style="padding:28px 36px 20px;border-bottom:1px solid #eceef1;">${linkedBrand}</td></tr>
<tr><td class="ipal-pad" style="padding:28px 36px 32px;font-family:${FONT};font-size:15px;line-height:1.65;color:#1f2937;">${content}</td></tr>
${footerLines ? `<tr><td class="ipal-pad" style="padding:20px 36px 28px;background:#f9fafb;font-family:${FONT};font-size:12px;line-height:1.6;color:#6b7280;">${footerLines}</td></tr>` : ''}
</table></td></tr></table></body></html>`
}
/** Site Settings → "Emails" tab (shown with `forms: { emailLayout: true }`). */
export const emailSettingsFields: Field[] = [
{
name: 'email',
type: 'group',
admin: { hideGutter: true },
fields: [
{
name: 'logo',
type: 'upload',
admin: { description: 'PNG or JPG for a light background — Gmail and Outlook do not show SVG. Empty = the site name.' },
label: 'E-mail logo',
relationTo: 'media',
},
{
name: 'accentColor',
type: 'text',
admin: { description: 'Hex, e.g. #017BD0 — top bar and section titles.' },
label: 'Accent colour',
validate: (value: unknown) => !value || /^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) || 'Use a hex colour, e.g. #017BD0.',
},
{ name: 'footer', type: 'textarea', admin: { description: 'E.g. company name and address.' }, label: 'Footer', localized: true },
],
label: false,
},
]
/** Neutral accent when the panel has none (plugin default, not a brand colour). */
const DEFAULT_ACCENT = '#111827'
type HookArgs = { data?: { form?: unknown; submissionData?: SubmissionValue[] }; req: PayloadRequest }
const mediaUrl = (media: unknown): string | undefined =>
media && typeof media === 'object' && 'url' in media && typeof media.url === 'string' ? media.url : undefined
/**
* form-builder `beforeEmail`: summary instead of the raw table + the layout.
* Never blocks sending — on any error the original e-mails go out (logged).
*/
export function buildEmailLayoutHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}) {
return async (emails: FormattedEmail[], { data, req }: HookArgs): Promise<FormattedEmail[]> => {
const { locale, payload } = req
try {
const formRef = data?.form
const formId = formRef && typeof formRef === 'object' && 'id' in formRef ? formRef.id : formRef
const [form, settings] = await Promise.all([
payload.findByID({ id: formId as number | string, collection: formsSlug as never, depth: 0, locale: locale as never, overrideAccess: true, req }),
payload.findGlobal({ slug: 'site-settings' as never, depth: 1, locale: locale as never, req }),
])
const s = settings as { email?: { accentColor?: string; footer?: string; logo?: unknown }; siteName?: string }
const accent = s.email?.accentColor || DEFAULT_ACCENT
const summary = renderSummaryHtml(buildSubmissionSummary((form as { fields?: BuilderField[] }).fields, data?.submissionData ?? []), { accent })
const serverURL = payload.config.serverURL?.replace(/\/$/, '')
const logo = mediaUrl(s.email?.logo)
const logoUrl = logo && /^https?:\/\//.test(logo) ? logo : logo && serverURL ? `${serverURL}${logo}` : undefined
return emails.map((email) => ({
...email,
html: wrapEmailHtml({
accent,
content: replaceSubmissionTable(email.html ?? '', summary),
...(s.email?.footer ? { footer: s.email.footer } : {}),
...(logoUrl ? { logoUrl } : {}),
...(s.siteName ? { siteName: s.siteName } : {}),
...(serverURL ? { siteUrl: serverURL } : {}),
}),
}))
} catch (err) {
payload.logger.error(`[ipal] E-mail layout skipped: ${(err as Error).message}`)
return emails
}
}
}
+40 -10
View File
@@ -1,13 +1,22 @@
import type { Field, Plugin } from 'payload'
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { Block, Field, Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
withShowWhen(builtinBlocks[key] as Block)
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
@@ -51,17 +60,38 @@ function hideEmails(fields: Field[]): Field[] {
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
const beforeEmail: BeforeEmail | undefined =
layout || forms.beforeEmail
? async (emails, args) => {
const laidOut = layout ? await layout(emails, args) : emails
return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut
}
: undefined
return formBuilderPlugin({
...(beforeEmail ? { beforeEmail } : {}),
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: {
checkbox: true,
email: true,
message: true,
number: true,
// every block carries "Show only when" (showWhen) — conditional fields and steps
checkbox: builtin('checkbox'),
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: builtin('date'),
email: withHint('email'),
message: builtin('message'),
number: withHint('number'),
payment: false,
select: true,
text: true,
textarea: true,
...forms.fields,
radio: builtin('radio'),
select: builtin('select'),
step: forms.fields?.step === false ? false : stepBlock,
text: withHint('text'),
textarea: withHint('textarea'),
time: forms.fields?.time === false ? false : timeBlock,
...Object.fromEntries(
// `true` keeps ipal's block (with "Show only when"); false / an object override it
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
),
},
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
+5
View File
@@ -1,3 +1,8 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+6 -1
View File
@@ -19,6 +19,8 @@ export type SubmitFormArgs = {
formId: string
/** Client IP — used for Turnstile and rate limiting. */
ip?: string
/** Page language — the form-builder reads the form (e-mail texts, labels) in it. */
locale?: string
/**
* Rate limit: max submissions per IP per minute. Defaults to 5.
* Set to 0 to disable (e.g. when a real limiter sits in front).
@@ -96,6 +98,7 @@ export async function submitForm({
data,
formId,
ip,
locale,
maxPerMinute = 5,
payload,
turnstileOnConfigError = 'allow',
@@ -143,11 +146,13 @@ export async function submitForm({
try {
const submission = await payload.create({
collection: 'form-submissions',
...(locale ? { locale: locale as never } : {}),
data: {
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
} as never,
})
+23
View File
@@ -1,3 +1,4 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { CollectionConfig, Field } from 'payload'
/**
@@ -25,22 +26,44 @@ export type FormsOption = {
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: false | string
/**
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
* the ipal layout when `emailLayout` is on.
*/
beforeEmail?: BeforeEmail
/**
* Name of the checkbox field treated as a GDPR consent gate. A form field
* with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'.
*/
consentFieldName?: string
/**
* Branded e-mails (emailLayout.ts): `{{*:table}}` becomes a readable summary
* (questions, option labels, grouped by step) and every e-mail gets a layout
* with the logo, accent colour and footer from Site Settings → Emails. Default false.
*/
emailLayout?: boolean
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
/** Multiple choice from a list (ipal). Default on. */
checkboxGroup?: boolean
country?: boolean
date?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
/** Single choice from a list. Default on. */
radio?: boolean
select?: boolean
state?: boolean
/** Step-by-step forms: divider between screens (ipal). Default on. */
step?: boolean
text?: boolean
textarea?: boolean
/** Time of day, <input type="time"> (ipal). Default on. */
time?: boolean
}
/**
* Override the forms collection. The plugin stays opinion-free about what a
+298
View File
@@ -0,0 +1,298 @@
'use client'
import type { ChangeEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, BuilderOption } from './builderTypes.js'
import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { useForm } from './useForm.js'
export type UseBuilderFormOptions = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
form: BuilderFormDoc
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
navigate?: (href: string) => void
/** After a successful submit — on top of the panel's analytics event. */
onSuccess?: (values: Record<string, unknown>) => void
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string
texts: BuilderFormTexts
/**
* Fields the page fills, by name (e.g. `{ subject: 'Ring · white gold · 0.70 ct' }`):
* kept in sync when the prop changes, read-only in BuilderForm, sent like any
* field. Names not in the form are ignored (the server rejects unknown fields).
*/
values?: Record<string, string>
}
/**
* Engine of every panel form: steps, values, per-step validation, Turnstile,
* submit through the server action, field errors from the server, redirect,
* analytics — and NO markup. <BuilderForm> renders a default on top of it; a
* form that looks or behaves differently (cards to pick from, a summary step,
* a custom field type) builds its own markup on the same hook:
*
* const f = useBuilderForm({ form, action, texts })
* <form onSubmit={f.submit}>
* {f.step.fields.map(({ field }) => <input key={field.name} {...f.getInputProps(field)} />)} // getTextareaProps, getSelectProps, getOptionProps
* <f.TurnstileWidget />
* {!f.isFirst && <button type="button" onClick={f.back}>{texts.back}</button>}
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
const [stepIndex, setStepIndex] = useState(0)
const [resultMessage, setResultMessage] = useState<null | string>(null)
const ts = useOptionalTurnstile()
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const shown = new Set(visibleInputs(values).map((field) => field.name))
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
return result
},
[action, texts.validation, visibleInputs],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
const f = useForm<Record<string, unknown>>({
errorFallback: texts.error,
// Page values are in the first render too — server HTML shows them before hydration.
initialValues: {
...initialBuilderValues(fields),
...Object.fromEntries(Object.entries(pageValues ?? {}).filter(([name]) => fields.some((field) => field.name === name))),
},
onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values)
if (form.confirmationType === 'redirect') {
const href = redirectHref ?? safeHref(form.redirect?.url)
if (href) {(navigate ?? ((h: string) => window.location.assign(h)))(href)}
}
},
requireTurnstile: ts.enabled,
submitAction,
validate,
})
const { setErrors, setField, setTurnstileToken } = f
// Page-supplied values follow the prop (a configurator changes them in the browser).
const fixedNames = useMemo(
() => new Set(Object.keys(pageValues ?? {}).filter((name) => fields.some((field) => field.name === name))),
[pageValues, fields],
)
const fixedKey = JSON.stringify(pageValues ?? {})
useEffect(() => {
for (const name of fixedNames) {setField(name, pageValues?.[name] ?? '')}
}, [fixedKey, fixedNames, setField])
/** True for a field whose value comes from the page (`values`) — show it, don't let the visitor edit it. */
const isFixed = useCallback((field: BuilderField) => Boolean(field.name && fixedNames.has(field.name)), [fixedNames])
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
const steps = useMemo(() => {
const shown = new Set(visibleFields(fields, f.values))
return splitSteps(fields, (field) => shown.has(field))
}, [fields, f.values])
// Turnstile token lives in the provider; the engine needs it at submit.
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
useEffect(() => {
if (!f.errorMessage) {return}
ts.reset()
const fieldError = serverFieldError.current
serverFieldError.current = null
if (fieldError) {
setErrors({ [fieldError.field]: fieldError.message })
setStepIndex(stepOfField(steps, fieldError.field))
}
}, [f.errorMessage])
const step = steps[Math.min(stepIndex, steps.length - 1)]
const isFirst = stepIndex === 0
const isLast = stepIndex >= steps.length - 1
/** Validates the current step and moves on. Returns false when the step has errors. */
const next = useCallback(() => {
const errors = validateBuilderFields(step.fields.map(({ field }) => field), f.values, texts)
setErrors(errors)
if (Object.keys(errors).length) {return false}
setStepIndex((i) => Math.min(i + 1, steps.length - 1))
return true
}, [step, f.values, texts, setErrors, steps.length])
const back = useCallback(() => setStepIndex((i) => Math.max(i - 1, 0)), [])
/** Jump to a step that's already been passed (a clickable progress bar). Forward jumps validate on the way. */
const goTo = useCallback(
(target: number) => {
if (target <= stepIndex) {return setStepIndex(Math.max(target, 0))}
for (let i = stepIndex; i < target; i++) {
const errors = validateBuilderFields(steps[i].fields.map(({ field }) => field), f.values, texts)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(i)
}
}
setStepIndex(Math.min(target, steps.length - 1))
},
[stepIndex, steps, f.values, texts, setErrors],
)
/** onSubmit of the <form>: Next on earlier steps, send on the last one. */
const submit = useCallback(
(e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
if (!isLast) {return void next()}
const errors = validate(f.values)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(stepOfField(steps, Object.keys(errors)[0]))
}
void f.handleSubmit()
},
[isLast, next, validate, f, setErrors, steps],
)
const fieldId = useCallback((field: BuilderField) => `ipal-f-${String(form.id)}-${field.name ?? ''}`, [form.id])
const errorId = useCallback((field: BuilderField) => `${fieldId(field)}-error`, [fieldId])
/** id, name, required and aria for any field's control (or its fieldset). */
const getFieldProps = useCallback(
(field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return {
id: fieldId(field),
name: field.name ?? undefined,
'aria-describedby': error ? errorId(field) : undefined,
'aria-invalid': error ? true : undefined,
required: Boolean(field.required),
}
},
[f.errors, errorId, fieldId],
)
const textValue = useCallback((name: string) => {
const value = f.values[name]
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · time · tel · checkbox. */
const getInputProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const base = { ...getFieldProps(field), autoComplete: autoCompleteFor(field) }
if (field.blockType === 'checkbox') {
return { ...base, type: 'checkbox', checked: f.values[name] === true, onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.checked) }
}
const type =
field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date'
: field.blockType === 'time' ? 'time'
: base.autoComplete === 'tel' ? 'tel'
: 'text'
return {
...base,
...(type === 'number' ? { inputMode: 'decimal' as const } : {}),
type,
onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(name),
}
},
[f, getFieldProps, textValue],
)
/** Props of a <textarea>. */
const getTextareaProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
onChange: (e: ChangeEvent<HTMLTextAreaElement>) => f.setField(field.name ?? '', e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of a <select> (render the options yourself — field.options). */
const getSelectProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
autoComplete: autoCompleteFor(field),
onChange: (e: ChangeEvent<HTMLSelectElement>) => f.setField(field.name ?? '', e.target.value),
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of one option's input in a radio group or checkboxGroup. */
const getOptionProps = useCallback(
(field: BuilderField, option: BuilderOption, i: number) => {
const name = field.name ?? ''
const id = `${fieldId(field)}-${i}`
if (field.blockType === 'checkboxGroup') {
const picked = Array.isArray(f.values[name]) ? (f.values[name] as string[]) : []
return {
id,
name,
type: 'checkbox',
checked: picked.includes(option.value),
onChange: (e: ChangeEvent<HTMLInputElement>) =>
f.setField(name, e.target.checked ? [...picked, option.value] : picked.filter((v) => v !== option.value)),
value: option.value,
}
}
return {
id,
name,
type: 'radio',
checked: f.values[name] === option.value,
onChange: () => f.setField(name, option.value),
required: Boolean(field.required) && i === 0,
value: option.value,
}
},
[f, fieldId],
)
return {
...f,
back,
errorId,
fieldId,
form,
getFieldProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
isFirst,
isFixed,
isLast,
next,
/** Message the server returned on success (Notifications → success). */
resultMessage,
step,
stepIndex,
steps,
submit,
total: steps.length,
TurnstileWidget: ts.TurnstileWidget,
}
}
export type BuilderFormApi = ReturnType<typeof useBuilderForm>
+46 -4
View File
@@ -1,13 +1,22 @@
import type { BasePayload } from 'payload'
import type { FieldCondition } from './builderTypes.js'
import { visibleFields } from './builderLogic.js'
/** A form-builder field, trimmed to what validation needs. */
type FormField = {
blockType?: string
label?: string
/** checkboxGroup limits. */
maxSelected?: null | number
minSelected?: null | number
name?: string
/** select / radio choices defined in the panel. */
/** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
/** "Show only when" — hidden fields are neither required nor stored. */
showWhen?: FieldCondition | null
}
type FormDoc = {
@@ -35,7 +44,13 @@ export type FormValidationResult =
| { ok: false; reason: 'not_found' }
/** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message'])
const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** HH:MM or HH:MM:SS (a time input), 00:00–23:59. */
const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
/**
* Keys injected by the captcha widget itself, not by the form definition.
@@ -63,7 +78,7 @@ const MAX_EMAIL_LENGTH = 254
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format'; value?: unknown }
type Checked = { error?: 'invalid_format' | 'required'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
@@ -76,6 +91,23 @@ function checkValue(field: FormField, value: unknown): Checked {
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'checkboxGroup': {
// string[] of distinct option values, within the panel's min/max.
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {return { error: 'invalid_format' }}
const picked = [...new Set(value as string[])]
const allowed = new Set((field.options ?? []).map((o) => String(o?.value)))
if (picked.some((v) => !allowed.has(v))) {return { error: 'invalid_format' }}
if (picked.length === 0) {return { value: undefined }}
if (field.minSelected && picked.length < field.minSelected) {return { error: 'required' }}
if (field.maxSelected && picked.length > field.maxSelected) {return { error: 'invalid_format' }}
return { value: picked }
}
case 'date': {
if (typeof value !== 'string' || !DATE.test(value.trim()) || Number.isNaN(Date.parse(value.trim()))) {
return { error: 'invalid_format' }
}
return { value: value.trim() }
}
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
@@ -94,6 +126,8 @@ function checkValue(field: FormField, value: unknown): Checked {
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
case 'time':
return typeof value === 'string' && TIME.test(value.trim()) ? { value: value.trim() } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
@@ -148,13 +182,21 @@ export async function validateSubmission(
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
)
const known = new Map(fields.map((f) => [f.name, f]))
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
const shown = new Set(visibleFields(form.fields, data))
const cleaned: Record<string, unknown> = {}
for (const field of fields) {
// Hidden by a condition: not required, not stored. The consent gate never hides —
// an editor can't switch GDPR consent off with a condition.
if (!shown.has(field) && field.name !== consentFieldName) {continue}
const value = data[field.name]
const isBlank =
value == null || (typeof value === 'string' && value.trim() === '') || value === false
value == null ||
(typeof value === 'string' && value.trim() === '') ||
value === false ||
(Array.isArray(value) && value.length === 0)
// GDPR consent gate: a field matching the consent name must be truthy
// (checked). Enforced independently of `required`, so it can't be weakened
+92
View File
@@ -0,0 +1,92 @@
import type { ReactNode } from 'react'
import type { AnalyticsProps } from '../analytics/Analytics.js'
import type { ConsentCookieMap } from '../consent/useConsent.js'
import type { PageStatsProps } from '../stats/PageStats.js'
import type { SiteShell } from './createContentHelpers.js'
import { Analytics } from '../analytics/Analytics.js'
import { ConsentProvider } from '../consent/ConsentContext.js'
import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { PageStats } from '../stats/PageStats.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { ThemeScript } from '../theme/ThemeScript.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = {
/** `defer` etc. for <Analytics>; `false` = no analytics tags at all. */
analytics?: false | Omit<AnalyticsProps, keyof SiteShell['analytics']>
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
banner?: false | ReactNode
children: ReactNode
/** The "cookie settings" button. Default `<CookieButton />`; your own or `false`. */
cookieButton?: false | ReactNode
/** Extra cookies per category to delete when consent is withdrawn. */
cookieMap?: ConsentCookieMap
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
jsonLd?: (null | Record<string, unknown> | undefined)[]
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
logEndpoint?: string
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
shell: SiteShell
/**
* Built-in statistics (ipalKit stats: true): mounts <PageStats>. `true` or
* `{ locale, endpoint }`. Default off.
*/
stats?: boolean | PageStatsProps
/**
* Light / dark theme from Site Settings → Theme: renders <ThemeScript> first,
* so the theme is on <html> before the first paint. Put <SiteProviders> first in
* <body> and add `suppressHydrationWarning` to <html>. Default false.
*/
theme?: boolean
}
/**
* The wiring every [locale] layout repeats — consent, Turnstile, analytics,
* site JSON-LD, media preconnect — in the right order (Analytics inside the
* consent provider, forms inside Turnstile). Renders no markup of its own:
* <html>, <body>, header, footer and <main> stay in the layout.
*
* const shell = await getSiteShell(locale)
* <body>
* <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
* <Header … /><main>{children}</main><Footer … />
* </SiteProviders>
* </body>
*
* Every part is replaceable or switchable off; for a fully custom tree use the
* providers themselves (consent.md, turnstile.md) — the shell data still fits.
*/
export function SiteProviders({
analytics,
banner,
children,
cookieButton,
cookieMap,
jsonLd = [],
logEndpoint,
preconnect = true,
shell,
stats = false,
theme = false,
}: SiteProvidersProps) {
return (
<>
{theme ? <ThemeScript {...shell.theme} /> : null}
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
<TurnstileProvider siteKey={shell.turnstileSiteKey}>{children}</TurnstileProvider>
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
{stats ? <PageStats {...(stats === true ? {} : stats)} /> : null}
</ConsentProvider>
</>
)
}

Some files were not shown because too many files have changed in this diff Show More