Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1413e96731 | ||
|
|
e1431a7c49 | ||
|
|
2c3195c4e1 | ||
|
|
4ec27d9ef0 | ||
|
|
305c564d13 | ||
|
|
166bf51e53 | ||
|
|
8b35986635 | ||
|
|
faa4ad679c | ||
|
|
23e033d7d7 | ||
|
|
f809526f1d | ||
|
|
46d30d4ecd | ||
|
|
a6eda2e3a3 |
@@ -13,7 +13,7 @@ export default async function LocaleLayout({ children, params }: Props) {
|
||||
return (
|
||||
<html lang={locale}>
|
||||
<body>
|
||||
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
|
||||
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
|
||||
<main>{children}</main>
|
||||
</SiteProviders>
|
||||
</body>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+304
-4
@@ -213,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';
|
||||
@@ -231,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';
|
||||
@@ -251,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';
|
||||
@@ -261,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';
|
||||
@@ -279,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';
|
||||
@@ -298,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';
|
||||
@@ -308,6 +398,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: 'textarea';
|
||||
@@ -335,6 +442,19 @@ export interface Form {
|
||||
* 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';
|
||||
@@ -345,6 +465,19 @@ export interface Form {
|
||||
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';
|
||||
@@ -362,6 +495,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: 'radio';
|
||||
@@ -372,10 +518,48 @@ export interface 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;
|
||||
@@ -701,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;
|
||||
};
|
||||
@@ -721,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;
|
||||
};
|
||||
@@ -728,6 +925,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
| T
|
||||
| {
|
||||
message?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -739,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;
|
||||
};
|
||||
@@ -758,6 +968,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
id?: T;
|
||||
};
|
||||
required?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -779,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;
|
||||
};
|
||||
@@ -790,6 +1013,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;
|
||||
};
|
||||
@@ -809,6 +1039,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
};
|
||||
minSelected?: T;
|
||||
maxSelected?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -820,6 +1056,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
width?: T;
|
||||
required?: T;
|
||||
defaultValue?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -838,6 +1080,12 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
id?: T;
|
||||
};
|
||||
required?: T;
|
||||
showWhen?:
|
||||
| T
|
||||
| {
|
||||
field?: T;
|
||||
values?: T;
|
||||
};
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
@@ -846,6 +1094,28 @@ export interface FormsSelect<T extends boolean = true> {
|
||||
| {
|
||||
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;
|
||||
};
|
||||
@@ -991,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;
|
||||
}
|
||||
@@ -1092,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.
|
||||
*/
|
||||
@@ -1100,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.
|
||||
*/
|
||||
@@ -1111,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.
|
||||
@@ -1206,6 +1500,7 @@ export interface SiteSettingsSelect<T extends boolean = true> {
|
||||
favicon?: T;
|
||||
defaultTheme?: T;
|
||||
allowThemeToggle?: T;
|
||||
themeToggleLabel?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
globalType?: T;
|
||||
@@ -1259,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
|
||||
@@ -1268,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
|
||||
|
||||
@@ -69,6 +69,7 @@ export default buildConfig({
|
||||
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,
|
||||
}),
|
||||
|
||||
@@ -8,6 +8,183 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
|
||||
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
|
||||
dopiero powyżej 20.
|
||||
|
||||
## 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
|
||||
|
||||
+3
-1
@@ -28,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) |
|
||||
|
||||
+14
-4
@@ -52,7 +52,7 @@ 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` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | 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` — 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 |
|
||||
@@ -138,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? |
|
||||
@@ -285,7 +287,8 @@ src/
|
||||
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
|
||||
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, { blocks }) — 404 z panelu
|
||||
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 # export { manifest as default } from lib/content + force-dynamic
|
||||
@@ -350,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.
|
||||
@@ -648,6 +652,9 @@ Skill: **ipal-nav**.
|
||||
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.
|
||||
- **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`
|
||||
@@ -769,7 +776,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
|---|---|---|
|
||||
| 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, { blocks, fallback })` (`/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 |
|
||||
@@ -780,6 +787,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
| 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 |
|
||||
@@ -804,6 +812,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
| 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 |
|
||||
@@ -817,6 +826,7 @@ projekcie → **ipal-plugin-gap**, nie kopia.
|
||||
| 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 |
|
||||
|
||||
@@ -53,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) ---
|
||||
@@ -197,7 +197,10 @@ 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' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
|
||||
"$(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: [...] }))" \
|
||||
@@ -274,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" \
|
||||
@@ -320,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`)
|
||||
}
|
||||
|
||||
|
||||
@@ -21,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`.
|
||||
|
||||
|
||||
|
||||
@@ -68,6 +68,9 @@ własny typ pola, suwak): nie kopiuj silnika — w kolejności:
|
||||
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**.
|
||||
|
||||
|
||||
@@ -153,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>
|
||||
```
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -41,7 +41,8 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
|
||||
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
|
||||
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
|
||||
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
|
||||
`not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md).
|
||||
`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()`,
|
||||
|
||||
@@ -38,6 +38,18 @@ własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) →
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -207,6 +207,7 @@ Teksty z panelu (**Cookie Settings**, per język) — puste pole = element się
|
||||
| `settingsDescription` | opis pod tytułem ustawień |
|
||||
| `alwaysActiveLabel` | znacznik przy „Niezbędne” zamiast wyłączonego przełącznika |
|
||||
| `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.
|
||||
|
||||
@@ -232,6 +233,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)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+35
-3
@@ -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ŚĆ
|
||||
@@ -303,12 +312,23 @@ export const generateStaticParams = route.generateStaticParams // SSG → <hea
|
||||
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
|
||||
|
||||
```tsx
|
||||
// src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers()
|
||||
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
// 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 default createNotFoundPage(content, { blocks: blockRegistry /*, fallback: <h1>404</h1> */ })
|
||||
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
|
||||
@@ -545,6 +565,18 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
|
||||
| 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 |
|
||||
| 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
|
||||
|
||||
+1
-1
@@ -171,7 +171,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
|
||||
(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, { blocks }) — BEZ headers() (pages.md).
|
||||
- [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 `●`;
|
||||
|
||||
@@ -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'
|
||||
|
||||
+34
-2
@@ -43,7 +43,7 @@ ipalKit({
|
||||
forms: {
|
||||
redirectRelationships: ['pages'], // formularz może przekierować na Page
|
||||
// fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
|
||||
// // select, radio, checkbox, checkboxGroup, message, step
|
||||
// // time, select, radio, checkbox, checkboxGroup, message, step
|
||||
},
|
||||
})
|
||||
```
|
||||
@@ -80,14 +80,20 @@ formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładk
|
||||
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**, select, **radio**, checkbox, **Checkbox group**,
|
||||
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
|
||||
@@ -117,6 +123,32 @@ po przecinku (pusto = gdy tamto pole jest wypełnione / zaznaczone). Puste `fiel
|
||||
- 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}`.
|
||||
|
||||
@@ -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
|
||||
|
||||
+13
-2
@@ -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
|
||||
@@ -227,8 +238,8 @@ export default route.Page
|
||||
export const generateMetadata = route.generateMetadata
|
||||
export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale
|
||||
|
||||
// app/(frontend)/not-found.tsx
|
||||
export default createNotFoundPage(content, { blocks: blockRegistry })
|
||||
// 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'
|
||||
|
||||
+14
-1
@@ -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
|
||||
|
||||
+50
-8
@@ -62,26 +62,68 @@ 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`, jedna linia (od 1.9.2):
|
||||
Projekt — dwa pliki w `app/(frontend)/[locale]/` (od 1.12.0, **wariant leniwy — zalecany**):
|
||||
|
||||
```tsx
|
||||
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
```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 default createNotFoundPage(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 }),
|
||||
})
|
||||
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
|
||||
|
||||
@@ -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
@@ -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'",
|
||||
|
||||
+64
-4
@@ -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ż
|
||||
@@ -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`
|
||||
@@ -1177,6 +1225,18 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
|
||||
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`.
|
||||
|
||||
+120
@@ -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
@@ -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).
|
||||
|
||||
@@ -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"`.
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.10.0",
|
||||
"version": "1.12.2",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -90,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,3 +11,7 @@ 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'
|
||||
|
||||
+13
-1
@@ -76,7 +76,19 @@ export {
|
||||
} from '../modules/i18n/index.js'
|
||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.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, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
|
||||
export type { TurnstileProps } from '../modules/turnstile/client.js'
|
||||
export type { TurnstileProps, TurnstileTheme } from '../modules/turnstile/client.js'
|
||||
|
||||
+9
-4
@@ -14,15 +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 { RenderForm } from '../modules/forms/RenderForm.js'
|
||||
export type { RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.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 } from '../modules/frontend/pageRoute.js'
|
||||
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
|
||||
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'
|
||||
|
||||
@@ -89,7 +89,8 @@ 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',
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
]
|
||||
|
||||
+11
-5
@@ -80,7 +80,7 @@ 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, stepBlock } from './modules/forms/builderBlocks.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).
|
||||
@@ -108,7 +108,7 @@ export {
|
||||
required,
|
||||
} from './modules/forms/validators.js'
|
||||
export type { Rule } from './modules/forms/validators.js'
|
||||
export type { ContentHelpers, PageJsonLdOptions, SiteShell } 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'
|
||||
@@ -172,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'
|
||||
@@ -214,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'
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -313,6 +313,8 @@ export function CookieBanner({
|
||||
<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)}
|
||||
}}
|
||||
@@ -327,7 +329,7 @@ export function CookieBanner({
|
||||
}
|
||||
|
||||
return (
|
||||
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" role="dialog">
|
||||
<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')}>
|
||||
|
||||
@@ -39,7 +39,14 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||
|
||||
type CookieSettingsData = {
|
||||
alwaysActiveLabel?: null | string
|
||||
buttons?: null | Partial<ConsentTexts['buttons']>
|
||||
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
|
||||
eyebrow?: null | string
|
||||
@@ -142,7 +149,7 @@ export async function getConsentTexts({
|
||||
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,
|
||||
|
||||
@@ -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'],
|
||||
}
|
||||
|
||||
Vendored
+16
-5
@@ -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).
|
||||
|
||||
@@ -4,6 +4,7 @@ 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'
|
||||
|
||||
@@ -18,7 +19,7 @@ import { useBuilderForm } from './useBuilderForm.js'
|
||||
export type BuilderFormClassNames = Partial<
|
||||
Record<
|
||||
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
|
||||
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
|
||||
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label'
|
||||
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
|
||||
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
|
||||
string
|
||||
@@ -48,9 +49,13 @@ export type BuilderFormProps = {
|
||||
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
|
||||
/** Appended to required labels, e.g. "*". Default: nothing. */
|
||||
requiredMark?: ReactNode
|
||||
turnstileTheme?: 'auto' | 'dark' | 'light'
|
||||
/** 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
|
||||
|
||||
/**
|
||||
@@ -74,14 +79,15 @@ export function BuilderForm({
|
||||
}: BuilderFormProps) {
|
||||
const f = useBuilderForm(options)
|
||||
const stepRef = useRef<HTMLDivElement>(null)
|
||||
const firstRender = useRef(true)
|
||||
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 (firstRender.current) {
|
||||
firstRender.current = false
|
||||
return
|
||||
}
|
||||
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()
|
||||
@@ -108,6 +114,18 @@ export function BuilderForm({
|
||||
|
||||
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)
|
||||
|
||||
@@ -3,6 +3,7 @@ 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'
|
||||
@@ -37,12 +38,15 @@ export type RenderFormProps = {
|
||||
richTextClassName?: string
|
||||
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
|
||||
texts: BuilderFormTexts
|
||||
turnstileTheme?: 'auto' | 'dark' | 'light'
|
||||
/** 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. */
|
||||
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
return {
|
||||
id: form.id,
|
||||
analytics: form.analytics,
|
||||
@@ -54,27 +58,42 @@ function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel form inside a block, in one line — server part of BuilderForm:
|
||||
* 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):
|
||||
*
|
||||
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||||
* // server
|
||||
* const prepared = prepareBuilderForm({ form, action: sendForm, locale })
|
||||
* <ProductConfigurator form={prepared} texts={formTexts} />
|
||||
* // client
|
||||
* <BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
|
||||
*
|
||||
* 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).
|
||||
* Returns null for an unpopulated form (an id or nothing).
|
||||
*/
|
||||
export function RenderForm({
|
||||
export function prepareBuilderForm({
|
||||
action,
|
||||
classNames,
|
||||
converters,
|
||||
form,
|
||||
linkOptions,
|
||||
locale,
|
||||
requiredMark,
|
||||
richTextClassName,
|
||||
texts,
|
||||
turnstileTheme,
|
||||
}: RenderFormProps) {
|
||||
}: PrepareBuilderFormArgs): null | PreparedBuilderForm {
|
||||
if (!form || typeof form !== 'object') {return null} // never a placeholder form
|
||||
|
||||
const rich = (data: unknown) =>
|
||||
@@ -93,17 +112,51 @@ export function RenderForm({
|
||||
: 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
|
||||
action={action.bind(null, String(form.id), locale)}
|
||||
{...prepared}
|
||||
classNames={classNames}
|
||||
confirmation={rich(form.confirmationMessage)}
|
||||
form={publicForm(form)}
|
||||
messages={messages}
|
||||
redirectHref={redirectHref}
|
||||
requiredMark={requiredMark}
|
||||
texts={texts}
|
||||
turnstileTheme={turnstileTheme}
|
||||
values={values}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ import type { Block, Field } from 'payload'
|
||||
* 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.
|
||||
@@ -61,6 +65,29 @@ 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: [
|
||||
@@ -112,3 +139,4 @@ const checkboxGroupBase: Block = {
|
||||
|
||||
export const stepBlock: Block = withShowWhen(stepBase)
|
||||
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
|
||||
export const timeBlock: Block = withShowWhen(timeBase)
|
||||
|
||||
@@ -15,7 +15,7 @@ export type FieldCondition = { field?: null | string; values?: null | string }
|
||||
|
||||
export type BuilderField = {
|
||||
blockName?: null | string
|
||||
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
||||
/** text · textarea · email · number · date · time · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
||||
blockType: string
|
||||
defaultValue?: unknown
|
||||
/** step */
|
||||
|
||||
@@ -6,7 +6,7 @@ import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-f
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
||||
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
|
||||
import { checkboxGroupBlock, stepBlock, timeBlock, withPlaceholder, withShowWhen } from './builderBlocks.js'
|
||||
import { buildEmailLayoutHook } from './emailLayout.js'
|
||||
|
||||
type AccessArgs = { req: { user?: unknown } }
|
||||
@@ -14,6 +14,8 @@ 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)
|
||||
@@ -68,7 +70,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
: undefined
|
||||
return formBuilderPlugin({
|
||||
...(beforeEmail ? { beforeEmail } : {}),
|
||||
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
|
||||
// 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: {
|
||||
@@ -76,18 +78,19 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
checkbox: builtin('checkbox'),
|
||||
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
||||
date: builtin('date'),
|
||||
email: builtin('email'),
|
||||
email: withHint('email'),
|
||||
message: builtin('message'),
|
||||
number: builtin('number'),
|
||||
number: withHint('number'),
|
||||
payment: false,
|
||||
radio: builtin('radio'),
|
||||
select: builtin('select'),
|
||||
step: forms.fields?.step === false ? false : stepBlock,
|
||||
text: builtin('text'),
|
||||
textarea: builtin('textarea'),
|
||||
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' && v !== true),
|
||||
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && k !== 'time' && v !== true),
|
||||
),
|
||||
},
|
||||
...(forms.redirectRelationships
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Panel field types: step-by-step forms + multiple choice (enabled by default).
|
||||
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||
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'
|
||||
|
||||
@@ -62,6 +62,8 @@ export type FormsOption = {
|
||||
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
|
||||
|
||||
@@ -23,6 +23,12 @@ export type UseBuilderFormOptions = {
|
||||
/** 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>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,7 +46,7 @@ export type UseBuilderFormOptions = {
|
||||
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
|
||||
* </form>
|
||||
*/
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
||||
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])
|
||||
@@ -65,7 +71,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
|
||||
const f = useForm<Record<string, unknown>>({
|
||||
errorFallback: texts.error,
|
||||
initialValues: initialBuilderValues(fields),
|
||||
// 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)
|
||||
@@ -78,7 +88,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
submitAction,
|
||||
validate,
|
||||
})
|
||||
const { setErrors, setTurnstileToken } = f
|
||||
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))
|
||||
@@ -167,7 +189,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
|
||||
}, [f.values])
|
||||
|
||||
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */
|
||||
/** Everything an <input> needs, by field type: text · email · number · date · time · tel · checkbox. */
|
||||
const getInputProps = useCallback(
|
||||
(field: BuilderField) => {
|
||||
const name = field.name ?? ''
|
||||
@@ -179,6 +201,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
field.blockType === 'email' ? 'email'
|
||||
: field.blockType === 'number' ? 'number'
|
||||
: field.blockType === 'date' ? 'date'
|
||||
: field.blockType === 'time' ? 'time'
|
||||
: base.autoComplete === 'tel' ? 'tel'
|
||||
: 'text'
|
||||
return {
|
||||
@@ -258,6 +281,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
getTextareaProps,
|
||||
goTo,
|
||||
isFirst,
|
||||
isFixed,
|
||||
isLast,
|
||||
next,
|
||||
/** Message the server returned on success (Notifications → success). */
|
||||
|
||||
@@ -46,6 +46,9 @@ export type FormValidationResult =
|
||||
/** Field block types that don't carry a submittable value. */
|
||||
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})?)?$/
|
||||
|
||||
@@ -123,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 }}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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'
|
||||
@@ -9,7 +10,9 @@ 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 = {
|
||||
@@ -30,6 +33,17 @@ export type SiteProvidersProps = {
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,9 +72,12 @@ export function SiteProviders({
|
||||
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}>
|
||||
@@ -68,6 +85,7 @@ export function SiteProviders({
|
||||
{banner === undefined ? <CookieBanner /> : banner || null}
|
||||
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
|
||||
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
|
||||
{stats ? <PageStats {...(stats === true ? {} : stats)} /> : null}
|
||||
</ConsentProvider>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -19,6 +19,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||||
import { archiveFieldName } from '../content/types.js'
|
||||
import { createHealthRoute } from '../health/createHealthRoute.js'
|
||||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
|
||||
import { createMcpRoute } from '../mcp/createMcpRoute.js'
|
||||
@@ -29,6 +30,7 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
|
||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||||
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
|
||||
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
|
||||
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
|
||||
type CreateContentHelpersArgs = {
|
||||
@@ -94,9 +96,30 @@ type CreateContentHelpersArgs = {
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */
|
||||
export type EntryJsonLdContext = {
|
||||
/** Archive page of the entry (title, slug). */
|
||||
archive: Record<string, unknown>
|
||||
/** Meta description (SEO tab or the site's description). */
|
||||
description?: string
|
||||
doc: Record<string, unknown>
|
||||
/** Absolute share-image URL. */
|
||||
image?: string
|
||||
locale: string
|
||||
siteName?: string
|
||||
/** Absolute canonical URL of the entry. */
|
||||
url: string
|
||||
}
|
||||
|
||||
export type PageJsonLdOptions = {
|
||||
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
|
||||
breadcrumbs?: boolean
|
||||
/**
|
||||
* The main node per content collection, instead of the article (`entryType`):
|
||||
* `{ products: (ctx) => buildProductJsonLd({…}), categories: (ctx) => buildWebPageJsonLd({ type: 'CollectionPage', … }) }`.
|
||||
* Return null to emit no main node. Breadcrumbs and FAQ still follow.
|
||||
*/
|
||||
entries?: Record<string, (ctx: EntryJsonLdContext) => null | Record<string, unknown>>
|
||||
/** schema.org type of archive entries. Default 'BlogPosting'. */
|
||||
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
|
||||
/**
|
||||
@@ -270,7 +293,10 @@ export function createContentHelpers({
|
||||
const image = meta.openGraph?.images?.[0]?.url
|
||||
const nodes: (null | Record<string, unknown>)[] = []
|
||||
|
||||
if (route.type === 'entry') {
|
||||
const entryNode = route.type === 'entry' ? opts.entries?.[route.collection] : undefined
|
||||
if (route.type === 'entry' && entryNode) {
|
||||
nodes.push(entryNode({ archive: route.archive, description: meta.description, doc, image, locale, siteName, url }))
|
||||
} else if (route.type === 'entry') {
|
||||
nodes.push(
|
||||
buildArticleJsonLd({
|
||||
type: opts.entryType ?? 'BlogPosting',
|
||||
@@ -572,8 +598,23 @@ export function createContentHelpers({
|
||||
|
||||
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
|
||||
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
|
||||
const homeSlug = await getHomeSlug(locale)
|
||||
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
|
||||
const settings = await getSettings(locale)
|
||||
const homeSlug = homeSlugFrom(settings)
|
||||
// Archive page per content collection → links to entries (categories, products…) resolve too.
|
||||
const archives = Object.fromEntries(
|
||||
(content?.collections ?? []).flatMap(({ slug }) => {
|
||||
const archive = (settings as Record<string, unknown>)[archiveFieldName(slug)]
|
||||
const archiveSlug = archive && typeof archive === 'object' ? (archive as { slug?: unknown }).slug : undefined
|
||||
return typeof archiveSlug === 'string' && archiveSlug ? [[slug, archiveSlug]] : []
|
||||
}),
|
||||
)
|
||||
return {
|
||||
config: needI18n('getLinkOptions'),
|
||||
locale,
|
||||
pagesSlug,
|
||||
...(homeSlug ? { homeSlug } : {}),
|
||||
...(Object.keys(archives).length ? { archives } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -677,6 +718,7 @@ export function createContentHelpers({
|
||||
formTexts,
|
||||
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
|
||||
settings: settings ?? {},
|
||||
theme: themeConfigFrom(settings),
|
||||
turnstileSiteKey: turnstile.siteKey,
|
||||
}
|
||||
})
|
||||
@@ -754,6 +796,8 @@ export type SiteShell = {
|
||||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||||
jsonLd: Record<string, unknown>[]
|
||||
settings: Record<string, unknown>
|
||||
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
|
||||
theme: ThemeConfig
|
||||
turnstileSiteKey: null | string
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.j
|
||||
import { RenderBlocks } from '../blocks/RenderBlocks.js'
|
||||
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
|
||||
import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getHomeSlug' | 'getSystemLinks'>> & Pick<
|
||||
ContentHelpers,
|
||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||
>
|
||||
@@ -17,16 +18,34 @@ type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
|
||||
|
||||
export type PageRouteOptions = {
|
||||
/** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */
|
||||
/**
|
||||
* Props for every block on top of `locale` and `isFirst` (true for the first
|
||||
* section — its heading is the page's only h1), computed once per page —
|
||||
* e.g. `{ formTexts, sendForm }` for form blocks.
|
||||
*/
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/** blockType → component (the project's registry). */
|
||||
blocks: BlockComponentMap
|
||||
/**
|
||||
* The homepage opened under its own slug (/pl/home): 'redirect' (default) — 308 to the
|
||||
* locale root, one URL per page (canonical already points there; Search Console reports
|
||||
* the alias as a duplicate otherwise). `false` — render it like any page.
|
||||
*/
|
||||
homeAlias?: 'redirect' | false
|
||||
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
|
||||
jsonLd?: boolean | PageJsonLdOptions
|
||||
/** Field with the blocks. Default 'layout'. */
|
||||
layoutField?: string
|
||||
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
|
||||
notFound: () => never
|
||||
/**
|
||||
* An address with no page (and no old-slug redirect):
|
||||
* - 'notFound' (default) — the 404 page;
|
||||
* - 'redirectHome' — 307 to the homepage in the same language (System Pages → Homepage;
|
||||
* needs `redirect`). No homepage assigned, or the homepage itself missing → 404;
|
||||
* - a function — your own decision, e.g. `({ locale }) => redirect(\`/${locale}/kontakt\`)`.
|
||||
*/
|
||||
onMissing?: 'notFound' | 'redirectHome' | ((ctx: { locale: string; segments: string[] }) => never | Promise<never>)
|
||||
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
|
||||
permanentRedirect: (url: string) => never
|
||||
/**
|
||||
@@ -63,7 +82,10 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||
*/
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, render } = options
|
||||
const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
if (onMissing === 'redirectHome' && !redirect) {
|
||||
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
|
||||
}
|
||||
const localeOf = (locale: string | undefined) => {
|
||||
const l = locale ?? helpers.i18n?.defaultLocale
|
||||
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||
@@ -75,6 +97,16 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
return helpers.generatePageMetadata(localeOf(locale), slug)
|
||||
}
|
||||
|
||||
async function missing(locale: string, segments: string[]): Promise<never> {
|
||||
if (typeof onMissing === 'function') {return onMissing({ locale, segments })}
|
||||
// segments.length: the homepage itself is missing — redirecting to it would loop.
|
||||
if (onMissing === 'redirectHome' && redirect && helpers.getSystemLinks && segments.length) {
|
||||
const [home] = await helpers.getSystemLinks(locale, ['homepage'])
|
||||
if (home?.href) {return redirect(home.href)}
|
||||
}
|
||||
return notFound()
|
||||
}
|
||||
|
||||
async function Page({ params }: PageArgs) {
|
||||
const { slug, locale: param } = await params
|
||||
const locale = localeOf(param)
|
||||
@@ -89,7 +121,16 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const route = await helpers.resolveRoute(locale, segments, 1)
|
||||
if (!route) {
|
||||
const target = await helpers.resolvePageRedirect(locale, segments)
|
||||
return target ? permanentRedirect(target) : notFound()
|
||||
if (target) {return permanentRedirect(target)}
|
||||
return missing(locale, segments)
|
||||
}
|
||||
if (homeAlias === 'redirect' && route.type !== 'home' && segments.length && helpers.getHomeSlug) {
|
||||
const homeSlug = await helpers.getHomeSlug(locale)
|
||||
if (homeSlug && segments.join('/') === homeSlug) {
|
||||
const [home] = helpers.getSystemLinks ? await helpers.getSystemLinks(locale, ['homepage']) : []
|
||||
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
|
||||
return permanentRedirect(home?.href ?? (multilingual ? `/${locale}` : '/'))
|
||||
}
|
||||
}
|
||||
const doc = route.doc
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
@@ -97,7 +138,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
<RenderBlocks
|
||||
blocks={doc[layoutField] as BlockData[] | undefined}
|
||||
components={blocks}
|
||||
enhanceProps={() => ({ locale, ...extra })}
|
||||
enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })}
|
||||
/>
|
||||
)
|
||||
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
|
||||
@@ -113,7 +154,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
|
||||
}
|
||||
|
||||
export type NotFoundPageOptions = {
|
||||
type NotFoundViewOptions = {
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
blocks: BlockComponentMap
|
||||
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
|
||||
@@ -121,31 +162,78 @@ export type NotFoundPageOptions = {
|
||||
layoutField?: string
|
||||
}
|
||||
|
||||
export type NotFoundPageOptions =
|
||||
| {
|
||||
/**
|
||||
* Lazy 404 (recommended): the project's server action returning
|
||||
* `renderNotFoundView(content, options, locale)`. Next puts the not-found tree
|
||||
* into the RSC payload of EVERY page; with `load` that tree is a small loader
|
||||
* and the content is fetched only when a 404 is shown. Without it every page
|
||||
* carries the whole 404 page in every locale.
|
||||
*/
|
||||
load: (locale: string) => Promise<ReactNode>
|
||||
}
|
||||
| ({ load?: undefined } & NotFoundViewOptions)
|
||||
|
||||
export type { NotFoundViewOptions }
|
||||
|
||||
type NotFoundHelpers = Pick<ContentHelpers, 'getConfiguredLocales' | 'getNotFoundPage' | 'i18n'>
|
||||
|
||||
async function localesOf(helpers: NotFoundHelpers): Promise<string[]> {
|
||||
const configured = await helpers.getConfiguredLocales()
|
||||
return configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
|
||||
}
|
||||
|
||||
async function notFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: string): Promise<ReactNode> {
|
||||
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
|
||||
const doc = await helpers.getNotFoundPage(locale)
|
||||
const layout = doc?.[layoutField] as BlockData[] | undefined
|
||||
if (!doc || !layout?.length) {return typeof fallback === 'function' ? fallback(locale) : fallback}
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
return <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} />
|
||||
}
|
||||
|
||||
/**
|
||||
* The 404 page from the panel in ONE locale — for the server action behind
|
||||
* `createNotFoundPage(content, { load })`. The locale comes from the browser,
|
||||
* so it is checked against the configured locales (anything else → default).
|
||||
*
|
||||
* // src/app/(frontend)/[locale]/notFoundView.ts
|
||||
* 'use server'
|
||||
* export async function loadNotFoundView(locale: string) {
|
||||
* return renderNotFoundView(content, { blocks: blockRegistry }, locale)
|
||||
* }
|
||||
*/
|
||||
export async function renderNotFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: unknown): Promise<ReactNode> {
|
||||
const locales = await localesOf(helpers)
|
||||
const safe = typeof locale === 'string' && locales.includes(locale) ? locale : (helpers.i18n?.defaultLocale ?? locales[0])
|
||||
return notFoundView(helpers, options, safe)
|
||||
}
|
||||
|
||||
/**
|
||||
* app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the
|
||||
* visitor's language, WITHOUT headers() (the route stays static): one view per
|
||||
* locale rendered here, <LocaleView> picks the one from the URL.
|
||||
* visitor's language, WITHOUT headers() (the route stays static).
|
||||
*
|
||||
* Lazy (recommended) — the content is fetched only when a 404 is shown:
|
||||
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
* import { loadNotFoundView } from './notFoundView'
|
||||
* export default createNotFoundPage(content, { load: loadNotFoundView })
|
||||
*
|
||||
* Eager — one view per locale rendered here, <LocaleView> picks the one from the
|
||||
* URL; Next ships all of them in the payload of every page:
|
||||
* export default createNotFoundPage(content, { blocks: blockRegistry })
|
||||
*/
|
||||
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
|
||||
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
|
||||
export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPageOptions) {
|
||||
return async function NotFoundPage() {
|
||||
const configured = await helpers.getConfiguredLocales()
|
||||
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
|
||||
const locales = await localesOf(helpers)
|
||||
const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
|
||||
if (options.load) {
|
||||
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} />
|
||||
}
|
||||
const eager = options
|
||||
const views = Object.fromEntries(
|
||||
await Promise.all(
|
||||
locales.map(async (locale) => {
|
||||
const doc = await helpers.getNotFoundPage(locale)
|
||||
const layout = doc?.[layoutField] as BlockData[] | undefined
|
||||
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
|
||||
if (!doc || !layout?.length) {return [locale, fb] as const}
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
|
||||
}),
|
||||
),
|
||||
await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)),
|
||||
)
|
||||
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
|
||||
return <LocaleView defaultLocale={defaultLocale} views={views} />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,17 @@ type BuildRevalidateHookArgs = {
|
||||
|
||||
type DocWithSlug = { slug?: unknown }
|
||||
|
||||
/**
|
||||
* Revalidation only makes sense inside a running Next server. Outside it
|
||||
* (`payload run`, seeds via tsx, migrations) next/cache throws "Invariant: static
|
||||
* generation store missing". `context.disableRevalidate` (Payload templates'
|
||||
* convention) skips it on purpose, e.g. in a bulk import.
|
||||
*/
|
||||
function shouldRevalidate(context: unknown): boolean {
|
||||
if (!process.env.NEXT_RUNTIME) {return false}
|
||||
return !(context && typeof context === 'object' && (context as { disableRevalidate?: unknown }).disableRevalidate)
|
||||
}
|
||||
|
||||
/** Resolve a doc's path in one locale (root for home). Null if no slug there. */
|
||||
function pathForLocale(
|
||||
doc: DocWithSlug,
|
||||
@@ -47,6 +58,8 @@ function pathForLocale(
|
||||
* Handles every locale, the root (home), AND a changed slug (revalidates both the
|
||||
* old and new path so neither goes stale). revalidatePath is injected — the
|
||||
* plugin never imports next/cache (safe under generate:importmap / plain Node).
|
||||
* Outside a Next server (no NEXT_RUNTIME: `payload run`, seeds, migrations) and
|
||||
* with `context: { disableRevalidate: true }` the hooks do nothing.
|
||||
*
|
||||
* // in your Media/Pages collection config, from a project file that CAN import next/cache:
|
||||
* import { revalidatePath } from 'next/cache'
|
||||
@@ -64,7 +77,8 @@ export function buildRevalidateHook({
|
||||
} {
|
||||
const locales = getLocaleCodes(config)
|
||||
|
||||
const afterChange: CollectionAfterChangeHook = ({ doc, previousDoc }) => {
|
||||
const afterChange: CollectionAfterChangeHook = ({ context, doc, previousDoc }) => {
|
||||
if (!shouldRevalidate(context)) {return doc}
|
||||
const seen = new Set<string>()
|
||||
for (const locale of locales) {
|
||||
// New path.
|
||||
@@ -85,7 +99,8 @@ export function buildRevalidateHook({
|
||||
return doc
|
||||
}
|
||||
|
||||
const afterDelete: CollectionAfterDeleteHook = ({ doc }) => {
|
||||
const afterDelete: CollectionAfterDeleteHook = ({ context, doc }) => {
|
||||
if (!shouldRevalidate(context)) {return doc}
|
||||
const seen = new Set<string>()
|
||||
for (const locale of locales) {
|
||||
const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
|
||||
|
||||
@@ -58,7 +58,7 @@ export function LanguageSwitcher({
|
||||
const current = locales.find((l) => l.code === currentLocale)
|
||||
|
||||
return (
|
||||
<div className={cn.root} data-ipal-langswitcher>
|
||||
<div className={cn.root} data-ipal-langswitcher data-nosnippet>
|
||||
<button
|
||||
aria-expanded={open}
|
||||
aria-haspopup="true"
|
||||
|
||||
@@ -17,10 +17,18 @@ export type BuildLinkFieldOptions = {
|
||||
appearances?: false | readonly LinkAppearanceOption[]
|
||||
/** Hide the label — for links that wrap something (a whole card, an image). */
|
||||
disableLabel?: boolean
|
||||
/**
|
||||
* Name of the generated TypeScript type. Default depends on the shape, so links of
|
||||
* different shapes never share one name (payload generate:types would keep only the
|
||||
* last one processed): `CmsLink`, `CmsLinkPlain` (appearances: false),
|
||||
* `CmsLinkNoLabel` (disableLabel), `CmsLinkPlainNoLabel` (both). Set it yourself
|
||||
* when you mix different `appearances` lists or `relationTo` values.
|
||||
*/
|
||||
interfaceName?: string
|
||||
/** Field name. Default 'link'. */
|
||||
name?: string
|
||||
/** Collection the "Page" option points at. Default 'pages'. */
|
||||
relationTo?: string
|
||||
relationTo?: readonly string[] | string
|
||||
required?: boolean
|
||||
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
|
||||
uploadTo?: string
|
||||
@@ -37,7 +45,8 @@ type SiblingWithType = { type?: string } | undefined
|
||||
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
|
||||
* (resolveLinkHref + the project's CMSLink) handles them all.
|
||||
*
|
||||
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
|
||||
* Generates a named TypeScript type in payload-types.ts — `CmsLink` for the default
|
||||
* shape, a suffixed name for others (see `interfaceName`). All are assignable to `CmsLink`.
|
||||
*
|
||||
* fields: [buildLinkField()] // single link
|
||||
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
|
||||
@@ -46,10 +55,13 @@ export function buildLinkField({
|
||||
name = 'link',
|
||||
appearances = ['primary', 'secondary', 'link'],
|
||||
disableLabel = false,
|
||||
interfaceName,
|
||||
relationTo = 'pages',
|
||||
required = false,
|
||||
uploadTo = 'media',
|
||||
}: BuildLinkFieldOptions = {}): GroupField {
|
||||
const hasAppearance = Boolean(appearances && appearances.length)
|
||||
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
|
||||
const fields: Field[] = [
|
||||
{
|
||||
type: 'row',
|
||||
@@ -73,13 +85,10 @@ export function buildLinkField({
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'relationship',
|
||||
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },
|
||||
relationTo,
|
||||
required,
|
||||
},
|
||||
// One collection → plain relation; several (pages + content entries) → polymorphic.
|
||||
typeof relationTo === 'string'
|
||||
? { name: 'page', type: 'relationship', admin: pageAdmin, relationTo, required }
|
||||
: { name: 'page', type: 'relationship', admin: pageAdmin, relationTo: [...relationTo], required },
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
@@ -107,7 +116,7 @@ export function buildLinkField({
|
||||
fields.push({ name: 'label', type: 'text', localized: true, required })
|
||||
}
|
||||
|
||||
if (appearances && appearances.length) {
|
||||
if (appearances && hasAppearance) {
|
||||
const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a))
|
||||
fields.push({
|
||||
name: 'appearance',
|
||||
@@ -122,7 +131,7 @@ export function buildLinkField({
|
||||
type: 'group',
|
||||
admin: { hideGutter: true },
|
||||
fields,
|
||||
interfaceName: 'CmsLink',
|
||||
interfaceName: interfaceName ?? `CmsLink${hasAppearance ? '' : 'Plain'}${disableLabel ? 'NoLabel' : ''}`,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { buildEntryPath } from '../content/paths.js'
|
||||
import { buildLocalizedPath } from '../i18n/index.js'
|
||||
|
||||
/**
|
||||
@@ -32,6 +33,12 @@ export type LinkValue = {
|
||||
}
|
||||
|
||||
export type ResolveLinkHrefOptions = {
|
||||
/**
|
||||
* Archive page slug per content collection in this locale (`{ categories: 'kategorie' }`) —
|
||||
* links to entries (buildLinkField({ relationTo: ['pages', 'categories'] })) become
|
||||
* /{locale}/{archive}/{entry}. getLinkOptions in lib/content fills it from Site Settings.
|
||||
*/
|
||||
archives?: Record<string, string>
|
||||
config: I18nConfig
|
||||
/**
|
||||
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
|
||||
@@ -39,6 +46,8 @@ export type ResolveLinkHrefOptions = {
|
||||
*/
|
||||
homeSlug?: Record<string, string> | string
|
||||
locale: string
|
||||
/** The pages collection — links to it are page paths, other collections are entries. Default 'pages'. */
|
||||
pagesSlug?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,7 +63,7 @@ export type ResolveLinkHrefOptions = {
|
||||
*/
|
||||
export function resolveLinkHref(
|
||||
link: LinkValue | null | undefined,
|
||||
{ config, homeSlug, locale }: ResolveLinkHrefOptions,
|
||||
{ archives, config, homeSlug, locale, pagesSlug = 'pages' }: ResolveLinkHrefOptions,
|
||||
): null | string {
|
||||
if (!link) {return null}
|
||||
|
||||
@@ -69,12 +78,22 @@ export function resolveLinkHref(
|
||||
return null
|
||||
}
|
||||
|
||||
// internal (default)
|
||||
const page = link.page
|
||||
// internal (default) — a page, or (polymorphic relation) an entry of a content collection
|
||||
let page = link.page
|
||||
let collection = pagesSlug
|
||||
if (page && typeof page === 'object' && 'relationTo' in page && 'value' in page) {
|
||||
collection = String((page as { relationTo: unknown }).relationTo)
|
||||
page = (page as { value: unknown }).value
|
||||
}
|
||||
if (!page || typeof page !== 'object') {return null}
|
||||
const slug = (page as { slug?: unknown }).slug
|
||||
if (typeof slug !== 'string' || !slug) {return null}
|
||||
|
||||
if (collection !== pagesSlug) {
|
||||
const archiveSlug = archives?.[collection]
|
||||
return archiveSlug ? buildEntryPath({ archiveSlug, entrySlug: slug, locale }) : null
|
||||
}
|
||||
|
||||
return (
|
||||
buildLocalizedPath({
|
||||
config,
|
||||
|
||||
@@ -42,6 +42,13 @@ export const MEDIA_SIZES = {
|
||||
export type MediaImageOptions = {
|
||||
/** Alt override (decorative images: ''). Default: the document's alt. */
|
||||
alt?: string
|
||||
/**
|
||||
* Dominant colour as the <img> background while it loads. The style stays after
|
||||
* load, so it would show through transparent pixels (white logo on a black box).
|
||||
* 'auto' (default): only for JPEG, which has no alpha channel. true: always
|
||||
* (opaque PNG/WebP photos). false: never.
|
||||
*/
|
||||
placeholderColor?: 'auto' | boolean
|
||||
/**
|
||||
* The LCP image (first visible image — usually the hero): loads eagerly with
|
||||
* fetchPriority="high". Exactly one per page; everything else is lazy.
|
||||
@@ -66,6 +73,9 @@ export type MediaImageProps = {
|
||||
width: number
|
||||
}
|
||||
|
||||
/** Formats that cannot be transparent — a background colour never shows through. */
|
||||
const NO_ALPHA = new Set(['image/jpeg', 'image/jpg', 'image/pjpeg'])
|
||||
|
||||
const asDoc = (resource: unknown): MediaDoc | null =>
|
||||
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
|
||||
|
||||
@@ -74,14 +84,18 @@ const asDoc = (resource: unknown): MediaDoc | null =>
|
||||
* a bare id). Width/height always come from the document — no layout shift.
|
||||
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
|
||||
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
|
||||
* blur-up and background colour.
|
||||
* blur-up and — for JPEG only, see `placeholderColor` — a background colour.
|
||||
*/
|
||||
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null {
|
||||
export function mediaImageProps(
|
||||
resource: unknown,
|
||||
{ alt, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
|
||||
): MediaImageProps | null {
|
||||
const doc = asDoc(resource)
|
||||
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
|
||||
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
|
||||
const blur = doc.placeholder?.blurDataURL ?? undefined
|
||||
const color = doc.placeholder?.color ?? undefined
|
||||
const useColor = placeholderColor === 'auto' ? NO_ALPHA.has(doc.mimeType ?? '') : placeholderColor
|
||||
const color = useColor ? (doc.placeholder?.color ?? undefined) : undefined
|
||||
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
|
||||
const style = {
|
||||
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
|
||||
|
||||
@@ -48,11 +48,12 @@ export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?
|
||||
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined
|
||||
if (!buffer) {return}
|
||||
const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
|
||||
const { dominant } = await sharp(buffer).stats()
|
||||
const { dominant, isOpaque } = await sharp(buffer).stats()
|
||||
const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0')
|
||||
data[field] = {
|
||||
blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`,
|
||||
color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}`,
|
||||
// Transparent images (logos, icons) get no colour — it would show through the alpha.
|
||||
color: isOpaque ? `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}` : null,
|
||||
}
|
||||
} catch (err) {
|
||||
// A placeholder is a nicety — never block the upload.
|
||||
|
||||
@@ -5,6 +5,8 @@ import type { ReactNode } from 'react'
|
||||
// Bundlers in the project resolve the same file either way.
|
||||
import { usePathname } from 'next/navigation.js'
|
||||
|
||||
import { localeFromPath } from './localeFromPath.js'
|
||||
|
||||
type LocaleViewProps = {
|
||||
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
|
||||
defaultLocale: string
|
||||
@@ -25,8 +27,6 @@ type LocaleViewProps = {
|
||||
* it also runs during SSR, so the HTML already contains the right language.
|
||||
*/
|
||||
export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
|
||||
const pathname = usePathname() ?? ''
|
||||
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
|
||||
const locale = segment in views ? segment : defaultLocale
|
||||
const locale = localeFromPath(usePathname() ?? '', Object.keys(views), defaultLocale)
|
||||
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
// '.js' is required: `next` has no package.json "exports" (see LocaleView.tsx).
|
||||
import { usePathname } from 'next/navigation.js'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { localeFromPath } from './localeFromPath.js'
|
||||
|
||||
type NotFoundLoaderProps = {
|
||||
defaultLocale: string
|
||||
/** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */
|
||||
load: (locale: string) => Promise<ReactNode>
|
||||
locales: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The 404 content, fetched only when the 404 is actually shown.
|
||||
*
|
||||
* Next puts the `not-found` tree of a layout into the RSC payload of EVERY page
|
||||
* under it (the router needs it for a client-side 404). A 404 page with real
|
||||
* content (often the homepage) rendered there in every locale multiplied the
|
||||
* size of each page. Here only this small component is in the payload; the
|
||||
* content comes from a server action on mount.
|
||||
*/
|
||||
export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) {
|
||||
const pathname = usePathname() ?? ''
|
||||
const locale = localeFromPath(pathname, locales, defaultLocale)
|
||||
const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
load(locale)
|
||||
.then((node) => {
|
||||
if (active) {setView({ locale, node })}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// the status is already 404 — without the content the page stays empty, the error goes to the console
|
||||
console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [load, locale])
|
||||
|
||||
return <>{view?.locale === locale ? view.node : null}</>
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* The locale from the first URL segment (`/en/...` → `en`), or `defaultLocale`
|
||||
* when the segment isn't one of `locales` (single-locale site, unknown prefix).
|
||||
*/
|
||||
export function localeFromPath(pathname: string, locales: readonly string[], defaultLocale: string): string {
|
||||
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
|
||||
return locales.includes(segment) ? segment : defaultLocale
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
|
||||
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
|
||||
import type { JSXConverters, JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
|
||||
|
||||
import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'
|
||||
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
|
||||
|
||||
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
|
||||
|
||||
export type RenderRichTextProps = {
|
||||
/** Wrapper class (e.g. Tailwind prose classes). */
|
||||
@@ -20,6 +23,46 @@ export type RenderRichTextProps = {
|
||||
* is needed here (unlike hand-rolled renderers that hardcode `.pl`).
|
||||
*/
|
||||
data: null | SerializedEditorState | undefined
|
||||
/**
|
||||
* Anchor ids on headings — the same ids as extractHeadings, so a
|
||||
* <TableOfContents> links to them. `true` = h2; or `{ levels, className }`
|
||||
* (className e.g. `scroll-mt-24` under a sticky header). Your own `heading`
|
||||
* converter still renders the heading; the id is added to what it returns.
|
||||
*/
|
||||
headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean
|
||||
}
|
||||
|
||||
type HeadingNode = { children?: unknown[]; tag: HeadingLevel }
|
||||
|
||||
/** Adds ids (and an optional class) to headings, on top of the project's converters. */
|
||||
function withHeadingIds(
|
||||
converters: JSXConvertersFunction | undefined,
|
||||
ids: Map<object, { id: string }>,
|
||||
className: string | undefined,
|
||||
): JSXConvertersFunction {
|
||||
return (args) => {
|
||||
const base: JSXConverters = converters ? converters(args) : args.defaultConverters
|
||||
const inner = base.heading
|
||||
return {
|
||||
...base,
|
||||
heading: (props: { node: HeadingNode; nodesToJSX: (a: { nodes: unknown[] }) => ReactNode[] }) => {
|
||||
const anchor = ids.get(props.node)
|
||||
const rendered: ReactNode =
|
||||
typeof inner === 'function'
|
||||
? (inner as (p: typeof props) => ReactNode)(props)
|
||||
: (() => {
|
||||
const Tag = props.node.tag
|
||||
return <Tag>{props.nodesToJSX({ nodes: props.node.children ?? [] })}</Tag>
|
||||
})()
|
||||
if (!anchor || !isValidElement(rendered)) {return rendered}
|
||||
const el = rendered as ReactElement<{ className?: string; id?: string }>
|
||||
const cls = [el.props.className, className].filter(Boolean).join(' ') || undefined
|
||||
// The project's converter owns the markup; only the id is added to what it returned.
|
||||
// eslint-disable-next-line @eslint-react/no-clone-element
|
||||
return cloneElement(el, { id: anchor.id, ...(cls ? { className: cls } : {}) })
|
||||
},
|
||||
} as JSXConverters
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,8 +91,19 @@ export type RenderRichTextProps = {
|
||||
* },
|
||||
* })
|
||||
* <RenderRichText data={page.content} converters={converters} />
|
||||
*
|
||||
* // long document with a table of contents (same ids on both sides):
|
||||
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
|
||||
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
|
||||
*/
|
||||
export function RenderRichText({ className, converters, data }: RenderRichTextProps) {
|
||||
export function RenderRichText({ className, converters, data, headingIds }: RenderRichTextProps) {
|
||||
if (!data) {return null}
|
||||
if (headingIds) {
|
||||
const opts = headingIds === true ? {} : headingIds
|
||||
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
|
||||
if (ids.size) {
|
||||
return <PayloadRichText className={className} converters={withHeadingIds(converters, ids, opts.className)} data={data} />
|
||||
}
|
||||
}
|
||||
return <PayloadRichText className={className} converters={converters} data={data} />
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import type { HeadingItem } from './headings.js'
|
||||
|
||||
export type TableOfContentsClassNames = {
|
||||
item?: string
|
||||
label?: string
|
||||
/** Every link. */
|
||||
link?: string
|
||||
/** Added to the link of the section being read. */
|
||||
linkActive?: string
|
||||
list?: string
|
||||
nav?: string
|
||||
}
|
||||
|
||||
export type TableOfContentsProps = {
|
||||
classNames?: TableOfContentsClassNames
|
||||
/** From extractHeadings — the same ids as the headings rendered with `headingIds`. */
|
||||
items: readonly ({ level?: HeadingItem['level'] } & Pick<HeadingItem, 'id' | 'text'>)[]
|
||||
/** Text above the list (from the panel). Also the nav's accessible name. Empty → none. */
|
||||
label?: null | string
|
||||
/**
|
||||
* Where the "reading line" is, as a fraction of the viewport height: the
|
||||
* current section is the last heading above it. Default 0.3.
|
||||
*/
|
||||
offset?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Table of contents with no styles: a <nav> with links to the headings. The
|
||||
* server renders the full list (works without JS); in the browser the link of
|
||||
* the section being read gets `aria-current="location"` and `classNames.linkActive`.
|
||||
* Hooks for CSS: data-ipal="toc", data-level on each item.
|
||||
*/
|
||||
export function TableOfContents({ classNames: cn = {}, items, label, offset = 0.3 }: TableOfContentsProps) {
|
||||
const [active, setActive] = useState<string | undefined>(items[0]?.id)
|
||||
|
||||
useEffect(() => {
|
||||
const headings = items.map((item) => document.getElementById(item.id)).filter((el): el is HTMLElement => el !== null)
|
||||
if (headings.length === 0) {return}
|
||||
const update = () => {
|
||||
const line = window.innerHeight * offset
|
||||
let current = headings[0].id
|
||||
for (const heading of headings) {
|
||||
if (heading.getBoundingClientRect().top <= line) {current = heading.id}
|
||||
}
|
||||
setActive(current)
|
||||
}
|
||||
update()
|
||||
window.addEventListener('scroll', update, { passive: true })
|
||||
window.addEventListener('resize', update)
|
||||
return () => {
|
||||
window.removeEventListener('scroll', update)
|
||||
window.removeEventListener('resize', update)
|
||||
}
|
||||
}, [items, offset])
|
||||
|
||||
if (items.length === 0) {return null}
|
||||
const text = label?.trim()
|
||||
return (
|
||||
<nav aria-label={text || undefined} className={cn.nav} data-ipal="toc">
|
||||
{text ? <p aria-hidden className={cn.label}>{text}</p> : null}
|
||||
<ol className={cn.list}>
|
||||
{items.map((item) => {
|
||||
const current = item.id === active
|
||||
return (
|
||||
<li className={cn.item} data-level={item.level} key={item.id}>
|
||||
<a
|
||||
aria-current={current ? 'location' : undefined}
|
||||
className={[cn.link, current ? cn.linkActive : undefined].filter(Boolean).join(' ') || undefined}
|
||||
href={`#${item.id}`}
|
||||
>
|
||||
{item.text}
|
||||
</a>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { Field, GroupField } from 'payload'
|
||||
|
||||
import { toSlug } from '../slug/buildSlugField.js'
|
||||
|
||||
export type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
|
||||
|
||||
/** One table-of-contents entry: the heading's anchor id, its plain text and level. */
|
||||
export type HeadingItem = { id: string; level: HeadingLevel; text: string }
|
||||
|
||||
export type ExtractHeadingsOptions = {
|
||||
/** Heading levels that get an anchor and a TOC entry. Default ['h2'] (sections of a document). */
|
||||
levels?: readonly HeadingLevel[]
|
||||
}
|
||||
|
||||
type LexicalNode = { children?: LexicalNode[]; tag?: string; text?: string; type?: string }
|
||||
|
||||
/** Plain text of a Lexical node (a heading with bold parts, links…). */
|
||||
export function headingText(node: unknown): string {
|
||||
const n = node as LexicalNode
|
||||
if (typeof n?.text === 'string') {return n.text}
|
||||
return (n?.children ?? []).map(headingText).join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the document in reading order and gives every heading of the chosen
|
||||
* levels an id: slug of its text (toSlug), repeats get "-2", "-3"; an empty
|
||||
* heading gets "section". Keyed by the node object, so RenderRichText puts
|
||||
* exactly these ids on exactly these headings.
|
||||
*/
|
||||
export function headingIds(data: unknown, { levels = ['h2'] }: ExtractHeadingsOptions = {}): Map<object, HeadingItem> {
|
||||
const wanted = new Set<string>(levels)
|
||||
const seen = new Map<string, number>()
|
||||
const out = new Map<object, HeadingItem>()
|
||||
const walk = (node: LexicalNode) => {
|
||||
if (node.type === 'heading' && node.tag && wanted.has(node.tag)) {
|
||||
const text = headingText(node).replace(/\s+/g, ' ').trim()
|
||||
const base = toSlug(text) || 'section'
|
||||
const count = (seen.get(base) ?? 0) + 1
|
||||
seen.set(base, count)
|
||||
out.set(node, { id: count === 1 ? base : `${base}-${count}`, level: node.tag as HeadingLevel, text })
|
||||
return
|
||||
}
|
||||
for (const child of node.children ?? []) {walk(child)}
|
||||
}
|
||||
const root = (data as { root?: LexicalNode } | null | undefined)?.root
|
||||
if (root) {walk(root)}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Table-of-contents entries of a rich-text field — the same ids RenderRichText
|
||||
* gives the headings with `headingIds`. Empty headings are left out.
|
||||
*
|
||||
* const items = extractHeadings(block.content) // h2 only
|
||||
* <TableOfContents items={items} label={block.tableOfContents?.label} />
|
||||
* <RenderRichText data={block.content} headingIds />
|
||||
*/
|
||||
export function extractHeadings(data: unknown, options: ExtractHeadingsOptions = {}): HeadingItem[] {
|
||||
return [...headingIds(data, options).values()].filter((h) => h.text.length > 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Panel switch for a table of contents on a text section: `show` + the label
|
||||
* above the list ("Contents"), localized. Named type `TableOfContentsSettings`.
|
||||
*
|
||||
* fields: [buildTableOfContentsField(), { name: 'content', type: 'richText' }]
|
||||
*/
|
||||
export function buildTableOfContentsField({ name = 'tableOfContents' }: { name?: string } = {}): GroupField {
|
||||
const fields: Field[] = [
|
||||
{ name: 'show', type: 'checkbox', admin: { description: 'List of the section headings (H2) with links to them — for long documents.' }, label: 'Show table of contents' },
|
||||
{
|
||||
name: 'label',
|
||||
type: 'text',
|
||||
admin: { condition: (_: unknown, s: { show?: boolean } | undefined) => Boolean(s?.show), description: 'Heading above the list, e.g. "Contents". Empty → none.' },
|
||||
label: 'Label',
|
||||
localized: true,
|
||||
},
|
||||
]
|
||||
return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: 'Table of contents' }
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
export { buildTableOfContentsField, extractHeadings, headingIds, headingText } from './headings.js'
|
||||
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './headings.js'
|
||||
export { lexicalToMarkdown } from './lexicalToMarkdown.js'
|
||||
export { RenderRichText } from './RenderRichText.js'
|
||||
export type { RenderRichTextProps } from './RenderRichText.js'
|
||||
|
||||
@@ -86,9 +86,12 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
|
||||
}
|
||||
|
||||
if (analytics) {
|
||||
src['script-src'].push('https://www.googletagmanager.com')
|
||||
src['connect-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')
|
||||
src['img-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')
|
||||
// Google's GA4/GTM CSP set. Wildcards are required: GA4 sends EU hits to
|
||||
// region1.google-analytics.com and some to *.analytics.google.com — allowing
|
||||
// only www.google-analytics.com blocks every hit ("data collection not active").
|
||||
src['script-src'].push('https://*.googletagmanager.com')
|
||||
src['connect-src'].push('https://*.google-analytics.com', 'https://*.analytics.google.com', 'https://*.googletagmanager.com')
|
||||
src['img-src'].push('https://*.google-analytics.com', 'https://*.googletagmanager.com')
|
||||
}
|
||||
|
||||
if (youtube) {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
'use client'
|
||||
import { useConfig, useDocumentInfo, useFormFields, useLocale } from '@payloadcms/ui'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export type MetaDescriptionCheckProps = {
|
||||
/** An empty description is filled from the page content on save (autoFill). */
|
||||
autoFill?: boolean
|
||||
/** SiteSettings global slug. */
|
||||
settingsSlug?: string
|
||||
/** Field on SiteSettings holding the site-wide fallback description. */
|
||||
siteDescriptionField?: string
|
||||
/** Field shown as the name of the page that has the same description. */
|
||||
titleField?: string
|
||||
}
|
||||
|
||||
type Warning = { text: string; tone: 'info' | 'warn' }
|
||||
|
||||
const norm = (v: unknown) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '')
|
||||
|
||||
/**
|
||||
* Hint under the meta description in the SEO tab. Google ignores a description
|
||||
* it sees on many pages and quotes page text instead (usually the footer), so
|
||||
* this flags a description that matches the site-wide fallback or another
|
||||
* document in the collection. Advisory only — saving is never blocked. Length
|
||||
* is already shown by plugin-seo's own counter.
|
||||
*/
|
||||
export function MetaDescriptionCheck({
|
||||
autoFill = true,
|
||||
settingsSlug = 'site-settings',
|
||||
siteDescriptionField = 'siteDescription',
|
||||
titleField = 'title',
|
||||
}: MetaDescriptionCheckProps) {
|
||||
const description = norm(useFormFields(([f]) => f['meta.description']?.value))
|
||||
const { id, collectionSlug } = useDocumentInfo()
|
||||
const { code: locale } = useLocale()
|
||||
const {
|
||||
config: {
|
||||
routes: { api },
|
||||
serverURL,
|
||||
},
|
||||
} = useConfig()
|
||||
const [warning, setWarning] = useState<null | Warning>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!description) {
|
||||
setWarning(
|
||||
autoFill
|
||||
? { text: 'Empty — on save it is filled from this page’s content. Writing your own is better.', tone: 'info' }
|
||||
: { text: 'Empty — the page gets the site-wide description, the same as every other page.', tone: 'warn' },
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!collectionSlug) {return}
|
||||
|
||||
const controller = new AbortController()
|
||||
const base = `${serverURL ?? ''}${api}`
|
||||
const get = async (url: string) => {
|
||||
const res = await fetch(url, { credentials: 'include', signal: controller.signal })
|
||||
return res.ok ? ((await res.json()) as Record<string, unknown>) : null
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const settings = await get(`${base}/globals/${settingsSlug}?depth=0&locale=${locale}`)
|
||||
if (settings && norm(settings[siteDescriptionField]) === description) {
|
||||
setWarning({
|
||||
text: 'Same as the site-wide description. Google ignores a description repeated across pages — write one about this page.',
|
||||
tone: 'warn',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const query = new URLSearchParams({
|
||||
depth: '0',
|
||||
limit: '1',
|
||||
locale,
|
||||
'where[meta.description][equals]': description,
|
||||
})
|
||||
if (id !== undefined && id !== null) {query.set('where[id][not_equals]', String(id))}
|
||||
const found = await get(`${base}/${collectionSlug}?${query}`)
|
||||
const twin = (found?.docs as Record<string, unknown>[] | undefined)?.[0]
|
||||
if (twin) {
|
||||
const name = norm(twin[titleField]) || String(twin.id)
|
||||
setWarning({
|
||||
text: `Same description as “${name}”. Google ignores a description repeated across pages — make each one unique.`,
|
||||
tone: 'warn',
|
||||
})
|
||||
return
|
||||
}
|
||||
setWarning(null)
|
||||
} catch {
|
||||
// aborted or offline — a hint is not worth an error
|
||||
}
|
||||
})()
|
||||
}, 600)
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [api, autoFill, collectionSlug, description, id, locale, serverURL, settingsSlug, siteDescriptionField, titleField])
|
||||
|
||||
if (!warning) {return null}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
style={{
|
||||
background:
|
||||
warning.tone === 'warn' ? 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))' : 'var(--theme-elevation-50)',
|
||||
border: `1px solid ${warning.tone === 'warn' ? 'var(--theme-warning-400, #ffb224)' : 'var(--theme-elevation-150)'}`,
|
||||
borderRadius: 4,
|
||||
fontSize: '0.85rem',
|
||||
marginBottom: '1.5rem',
|
||||
padding: '0.6rem 0.9rem',
|
||||
}}
|
||||
>
|
||||
{warning.text}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { HTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export type NoSnippetProps = {
|
||||
/**
|
||||
* Wrapper element. Only div, section and span — Google honours
|
||||
* `data-nosnippet` on those and ignores it on footer, nav, aside and the rest.
|
||||
* Default 'div'.
|
||||
*/
|
||||
as?: 'div' | 'section' | 'span'
|
||||
children?: ReactNode
|
||||
} & HTMLAttributes<HTMLElement>
|
||||
|
||||
/**
|
||||
* Keeps its contents out of Google's search snippets (`data-nosnippet`). The
|
||||
* text is still crawled and indexed — Google just won't quote it under a
|
||||
* result.
|
||||
*
|
||||
* Use it for text that repeats on every page: the footer's address, hours and
|
||||
* phone, a contact strip, a "book a visit" call to action. Google picks snippet
|
||||
* text itself when it thinks it fits the query better than the meta
|
||||
* description; for a brand search that is the contact block, so every sitelink
|
||||
* ends up showing the same address. The address stays available to Google
|
||||
* through the LocalBusiness JSON-LD.
|
||||
*
|
||||
* Never wrap <main> — that's the text the snippet should come from.
|
||||
*
|
||||
* <footer>
|
||||
* <NoSnippet>…address, hours, phone, links…</NoSnippet>
|
||||
* </footer>
|
||||
*/
|
||||
export function NoSnippet({ as: Tag = 'div', children, ...rest }: NoSnippetProps) {
|
||||
return (
|
||||
<Tag {...rest} data-nosnippet="">
|
||||
{children}
|
||||
</Tag>
|
||||
)
|
||||
}
|
||||
@@ -1,12 +1,23 @@
|
||||
import type { CollectionBeforeChangeHook } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { describeFromMarkdown } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
/**
|
||||
* Maps document fields to SEO meta fields for auto-fill.
|
||||
* Defaults match the Payload website template (title → meta.title).
|
||||
*/
|
||||
export type AutoFillMapping = {
|
||||
/** Document field used to fill meta.description when empty. */
|
||||
/**
|
||||
* Block layout field to derive meta.description from when it's empty and the
|
||||
* `description` field gives nothing. Default 'layout'; false turns it off.
|
||||
*/
|
||||
content?: false | string
|
||||
/** Document field used to fill meta.description when empty. Tried before `content`. */
|
||||
description?: string
|
||||
/** Target length of a description derived from `content`. Default 155. */
|
||||
descriptionLength?: number
|
||||
/** Document field used to fill meta.title when empty. Default: 'title'. */
|
||||
title?: string
|
||||
}
|
||||
@@ -27,32 +38,49 @@ function readString(value: unknown): string | undefined {
|
||||
* editor typed. This runs server-side on every create/update, so editors get
|
||||
* sensible meta without clicking "auto-generate".
|
||||
*
|
||||
* Every page gets its own description: from the `description` field when one
|
||||
* is mapped, otherwise from the page's own blocks. Without it, pages fall back
|
||||
* to the one site-wide description, and Google — seeing the same text on every
|
||||
* page — ignores it and quotes the footer instead.
|
||||
*
|
||||
* The plugin doesn't know the client's collection shape, so the field mapping
|
||||
* is configurable; defaults follow the website template.
|
||||
*/
|
||||
export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): CollectionBeforeChangeHook {
|
||||
const titleField = mapping.title ?? 'title'
|
||||
const descriptionField = mapping.description
|
||||
const contentField = mapping.content === undefined ? 'layout' : mapping.content
|
||||
const descriptionLength = mapping.descriptionLength ?? 155
|
||||
|
||||
return ({ data }) => {
|
||||
if (!data) {return data}
|
||||
return ({ context, data, originalDoc }) => {
|
||||
if (!data || isAutoFillSkipped(context)) {return data}
|
||||
|
||||
// plugin-seo stores meta as a group under `meta`
|
||||
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
|
||||
// A partial update (REST PATCH, payload.update with a few fields) carries
|
||||
// only what changed — read the rest from the stored document, so a saved
|
||||
// description isn't treated as empty and replaced.
|
||||
const stored = (originalDoc?.meta as Record<string, unknown> | undefined) ?? {}
|
||||
const current = (key: string) => (key in meta ? meta[key] : stored[key])
|
||||
const source = (field: string) => (field in data ? data[field] : originalDoc?.[field])
|
||||
|
||||
// Fill meta.title from the document title when empty
|
||||
if (!readString(meta.title)) {
|
||||
const sourceTitle = readString(data[titleField])
|
||||
if (!readString(current('title'))) {
|
||||
const sourceTitle = readString(source(titleField))
|
||||
if (sourceTitle) {meta.title = sourceTitle}
|
||||
}
|
||||
|
||||
// Fill meta.description from a configured field when empty
|
||||
if (descriptionField && !readString(meta.description)) {
|
||||
const sourceDescription = readString(data[descriptionField])
|
||||
// Fill meta.description from a configured field, else from the page content
|
||||
if (!readString(current('description'))) {
|
||||
const sourceDescription =
|
||||
(descriptionField && readString(source(descriptionField))) ||
|
||||
(contentField &&
|
||||
describeFromMarkdown(blocksToMarkdown(source(contentField)), descriptionLength)) ||
|
||||
undefined
|
||||
if (sourceDescription) {meta.description = sourceDescription}
|
||||
}
|
||||
|
||||
data.meta = meta
|
||||
if (data.meta !== undefined || Object.keys(meta).length) {data.meta = meta}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
type ProductPrice = {
|
||||
amount: number
|
||||
currency: string
|
||||
/** 'exact' → Offer.price; 'from' → minPrice (a starting price, not a promise). */
|
||||
kind?: 'exact' | 'from'
|
||||
}
|
||||
|
||||
type ProductJsonLdArgs = {
|
||||
/** schema.org availability, e.g. 'MadeToOrder', 'InStock'. Default 'InStock' when a price is given. */
|
||||
availability?: string
|
||||
brand?: string
|
||||
category?: string
|
||||
description?: string
|
||||
/** Absolute image URL. */
|
||||
image?: string
|
||||
name: string
|
||||
/** Only a real price from the panel — no price (on request) → no Offer at all. */
|
||||
price?: null | ProductPrice
|
||||
sku?: string
|
||||
/** Absolute URL of the product page (also its @id). */
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* schema.org Product for a catalog entry: name, SKU, image, category, brand and —
|
||||
* only when the panel has one — an Offer. A product "on request" gets no Offer:
|
||||
* an invented or estimated price in structured data misleads search results.
|
||||
*
|
||||
* createContentHelpers({ pageJsonLd: { entries: {
|
||||
* products: ({ doc, url, image }) => buildProductJsonLd({ name: doc.title, sku: doc.sku, url, image, … }),
|
||||
* } } })
|
||||
*/
|
||||
export function buildProductJsonLd({
|
||||
name,
|
||||
availability,
|
||||
brand,
|
||||
category,
|
||||
description,
|
||||
image,
|
||||
price,
|
||||
sku,
|
||||
url,
|
||||
}: ProductJsonLdArgs): Record<string, unknown> {
|
||||
const offer =
|
||||
price && Number.isFinite(price.amount) && price.currency
|
||||
? {
|
||||
'@type': 'Offer',
|
||||
availability: `https://schema.org/${availability ?? 'InStock'}`,
|
||||
priceCurrency: price.currency,
|
||||
url,
|
||||
...(price.kind === 'from'
|
||||
? { priceSpecification: { '@type': 'PriceSpecification', minPrice: price.amount, priceCurrency: price.currency } }
|
||||
: { price: price.amount }),
|
||||
}
|
||||
: undefined
|
||||
return {
|
||||
name,
|
||||
'@context': 'https://schema.org',
|
||||
'@id': url,
|
||||
'@type': 'Product',
|
||||
url,
|
||||
...(sku ? { sku } : {}),
|
||||
...(description ? { description } : {}),
|
||||
...(image ? { image } : {}),
|
||||
...(category ? { category } : {}),
|
||||
...(brand ? { brand: { name: brand, '@type': 'Brand' } } : {}),
|
||||
...(offer ? { offers: offer } : {}),
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Field, FieldHook, TextareaField } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { mdToPlain, truncate } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
type BuildSummaryFieldArgs = {
|
||||
/** Auto-fill from page content when the editor leaves it empty. Default true. */
|
||||
@@ -19,26 +21,6 @@ type BuildSummaryFieldArgs = {
|
||||
overrides?: Partial<TextareaField>
|
||||
}
|
||||
|
||||
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
|
||||
function mdToPlain(md: string): string {
|
||||
return md
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
|
||||
.replace(/^#{1,6}\s+/gm, '') // heading markers
|
||||
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
|
||||
.replace(/[*_~`]/g, '') // inline emphasis/code marks
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** Truncate at a word boundary, adding an ellipsis when cut. */
|
||||
function truncate(text: string, max: number): string {
|
||||
if (text.length <= max) {return text}
|
||||
const slice = text.slice(0, max)
|
||||
const lastSpace = slice.lastIndexOf(' ')
|
||||
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
|
||||
}
|
||||
|
||||
/**
|
||||
* A localized `aiSummary` textarea — a concise, human-written (or auto-derived)
|
||||
* description of the page, richer than the SEO meta description. It's the
|
||||
@@ -69,7 +51,8 @@ export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {
|
||||
overrides = {},
|
||||
} = args
|
||||
|
||||
const autofillHook: FieldHook = ({ data, value }) => {
|
||||
const autofillHook: FieldHook = ({ context, data, value }) => {
|
||||
if (isAutoFillSkipped(context)) {return value}
|
||||
if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary
|
||||
if (!data || typeof data !== 'object') {return value}
|
||||
const layout = (data as Record<string, unknown>)[layoutField]
|
||||
|
||||
@@ -142,6 +142,8 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
|
||||
locale,
|
||||
order: site.order,
|
||||
separator: site.separator,
|
||||
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
|
||||
siteDescription: site.siteDescription,
|
||||
siteName: site.siteName,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ export { buildMetadata } from './buildMetadata.js'
|
||||
export type { PageMetadata } from './buildMetadata.js'
|
||||
export { buildNoindexField } from './buildNoindexField.js'
|
||||
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
|
||||
export { buildProductJsonLd } from './buildProductJsonLd.js'
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
|
||||
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
|
||||
@@ -48,6 +49,7 @@ export { collectSiteIndex } from './siteIndex.js'
|
||||
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
|
||||
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
|
||||
export type { SitemapStyleOptions } from './sitemapStyle.js'
|
||||
export { SKIP_AUTO_FILL } from './skipAutoFill.js'
|
||||
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
|
||||
export type { SeoMeta, SeoOption } from './types.js'
|
||||
export { validateFaviconField } from './validateFavicon.js'
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
|
||||
export function mdToPlain(md: string): string {
|
||||
return md
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
|
||||
.replace(/^#{1,6}\s+/gm, '') // heading markers
|
||||
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
|
||||
.replace(/[*_~`]/g, '') // inline emphasis/code marks
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** Truncate at a word boundary, adding an ellipsis when cut. */
|
||||
export function truncate(text: string, max: number): string {
|
||||
if (text.length <= max) {return text}
|
||||
const slice = text.slice(0, max)
|
||||
const lastSpace = slice.lastIndexOf(' ')
|
||||
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
|
||||
}
|
||||
|
||||
/** Ensure a fragment ends like a sentence, so joined fragments don't run together. */
|
||||
function terminate(text: string): string {
|
||||
return /[.!?…:]$/.test(text) ? text : `${text}.`
|
||||
}
|
||||
|
||||
/**
|
||||
* A meta description from a page's Markdown (blocksToMarkdown output).
|
||||
*
|
||||
* Headings are skipped while there's body text — they usually repeat the page
|
||||
* title, which Google already shows above the snippet. Whole sentences are
|
||||
* kept up to `max`; a first sentence longer than that is cut at a word
|
||||
* boundary. Returns '' when the content has no text.
|
||||
*/
|
||||
export function describeFromMarkdown(md: string, max = 155): string {
|
||||
const parts = md.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
|
||||
const body = parts.filter((p) => !/^#{1,6}\s/.test(p) && !/^!\[/.test(p))
|
||||
const source = (body.length ? body : parts).map(mdToPlain).filter(Boolean).map(terminate)
|
||||
const text = source.join(' ')
|
||||
if (!text) {return ''}
|
||||
if (text.length <= max) {return text}
|
||||
|
||||
// Longest run of whole sentences that fits.
|
||||
const sentences = text.match(/[^.!?…]+[.!?…]+(?=\s|$)/g) ?? []
|
||||
let out = ''
|
||||
for (const s of sentences) {
|
||||
const next = `${out} ${s.trim()}`.trim()
|
||||
if (next.length > max) {break}
|
||||
out = next
|
||||
}
|
||||
return out || truncate(text, max)
|
||||
}
|
||||
@@ -25,6 +25,39 @@ const titleOverrideField: Field = {
|
||||
localized: true,
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin hint right under meta.description (MetaDescriptionCheck): empty,
|
||||
* same as the site-wide description, or same as another document's.
|
||||
*/
|
||||
function descriptionCheckField(seo: SeoOption): Field | null {
|
||||
if (seo.descriptionCheck === false) {return null}
|
||||
const autoFill =
|
||||
seo.autoFill !== false && (seo.autoFill?.content !== false || Boolean(seo.autoFill?.description))
|
||||
return {
|
||||
name: 'descriptionCheck',
|
||||
type: 'ui',
|
||||
admin: {
|
||||
components: {
|
||||
Field: {
|
||||
clientProps: {
|
||||
autoFill,
|
||||
titleField: (seo.autoFill && seo.autoFill.title) || 'title',
|
||||
...(seo.descriptionCheck ?? {}),
|
||||
},
|
||||
path: '@intecion/ipal-kit/admin#MetaDescriptionCheck',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts `extra` right after the description field (end of the group if it's missing). */
|
||||
function afterDescription(fields: Field[], extra: Field | null): Field[] {
|
||||
if (!extra) {return fields}
|
||||
const at = fields.findIndex((f) => 'name' in f && f.name === 'description')
|
||||
return at === -1 ? [...fields, extra] : [...fields.slice(0, at + 1), extra, ...fields.slice(at + 1)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures @payloadcms/plugin-seo from IPAL's SeoOption.
|
||||
*
|
||||
@@ -37,7 +70,11 @@ const titleOverrideField: Field = {
|
||||
export function buildSeoPlugin({ seo, uploadsCollection = 'media' }: BuildSeoPluginArgs): Plugin {
|
||||
return seoPlugin({
|
||||
collections: seo.collections,
|
||||
fields: ({ defaultFields }) => [...defaultFields, titleOverrideField, ...(seo.fields ?? [])],
|
||||
fields: ({ defaultFields }) => [
|
||||
...afterDescription(defaultFields, descriptionCheckField(seo)),
|
||||
titleOverrideField,
|
||||
...(seo.fields ?? []),
|
||||
],
|
||||
uploadsCollection,
|
||||
...(seo.generateTitle && { generateTitle: seo.generateTitle }),
|
||||
...(seo.generateDescription && { generateDescription: seo.generateDescription }),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* `payload.update({ …, context: { ipalSkipAutoFill: true } })` — the save fills nothing
|
||||
* automatically (meta title/description, AI summary). For data migrations and scripts that
|
||||
* must write exactly what they set, nothing generated on top. Same idea as Payload's
|
||||
* `context.disableRevalidate`.
|
||||
*/
|
||||
export const SKIP_AUTO_FILL = 'ipalSkipAutoFill'
|
||||
|
||||
export function isAutoFillSkipped(context: unknown): boolean {
|
||||
return Boolean(context && typeof context === 'object' && (context as Record<string, unknown>)[SKIP_AUTO_FILL])
|
||||
}
|
||||
@@ -17,6 +17,19 @@ export type SeoOption = {
|
||||
autoFill?: AutoFillMapping | false
|
||||
/** Collection slugs that receive SEO meta fields, e.g. ['pages', 'posts']. */
|
||||
collections: string[]
|
||||
/**
|
||||
* Hint under the meta description in the admin when it's empty, or the same
|
||||
* as the site-wide description or another document's. Advisory, never blocks
|
||||
* saving. Point it at your SiteSettings when the slugs differ; false hides it.
|
||||
*/
|
||||
descriptionCheck?:
|
||||
| {
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/** Field holding the site-wide description. Default 'siteDescription'. */
|
||||
siteDescriptionField?: string
|
||||
}
|
||||
| false
|
||||
/** Extra fields appended to the SEO group in the admin. */
|
||||
fields?: Field[]
|
||||
/** Optional: customize how meta descriptions are generated. */
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
'use client'
|
||||
import { useEffect, useRef } from 'react'
|
||||
// .js extension: Node's ESM resolution (this plugin's tsconfig) can't find
|
||||
// 'next/navigation' without it.
|
||||
import { usePathname } from 'next/navigation.js'
|
||||
|
||||
import { useConsentContext } from '../consent/ConsentContext.js'
|
||||
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js'
|
||||
|
||||
/** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */
|
||||
export const VISITOR_COOKIE = 'ipal_vid'
|
||||
|
||||
function readCookie(name: string): string | undefined {
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${name}=`))
|
||||
?.split('=')[1]
|
||||
}
|
||||
|
||||
function ensureVisitorId(): string {
|
||||
const existing = readCookie(VISITOR_COOKIE)
|
||||
if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing}
|
||||
const bytes = new Uint8Array(16)
|
||||
globalThis.crypto.getRandomValues(bytes)
|
||||
const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
const secure = location.protocol === 'https:' ? ';secure' : ''
|
||||
document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
|
||||
return id
|
||||
}
|
||||
|
||||
export type PageStatsProps = {
|
||||
/** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */
|
||||
endpoint?: string
|
||||
/** Current locale code, stored with the visit. */
|
||||
locale?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in statistics: sends one beacon per page view to the hit endpoint.
|
||||
*
|
||||
* - **Everyone, no consent needed** — nothing is stored in the browser; the
|
||||
* server joins page views into a visit with a daily-salted hash it can't
|
||||
* reverse, and keeps no IP.
|
||||
* - **With analytics consent** (the same category that turns on GA4) — sets the
|
||||
* `ipal_vid` cookie with a random id, so the panel can show that visitor's
|
||||
* history across days. Withdrawing consent deletes the cookie.
|
||||
*
|
||||
* Renders nothing. Mount once in the locale layout, INSIDE <ConsentProvider>.
|
||||
*/
|
||||
export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) {
|
||||
const pathname = usePathname()
|
||||
const { texts } = useConsentContext()
|
||||
const firstHit = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
if (!pathname) {return}
|
||||
const body: Record<string, string> = { p: pathname }
|
||||
// the external referrer belongs to the landing page only
|
||||
if (firstHit.current && document.referrer) {body.r = document.referrer}
|
||||
firstHit.current = false
|
||||
if (locale) {body.l = locale}
|
||||
// The cookie, not context state: on a full page load this effect runs before
|
||||
// useConsent has read the cookie, so state would still say "no consent".
|
||||
if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()}
|
||||
|
||||
const json = JSON.stringify(body)
|
||||
if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) {
|
||||
void fetch(endpoint, { body: json, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST' }).catch(() => {})
|
||||
}
|
||||
// texts.version is read, not a trigger: a policy change isn't a page view
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pathname, endpoint, locale])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Nav link to /admin/stats (admin.components.afterNavLinks). */
|
||||
export function StatsNavLink({ adminRoute = '/admin' }: { adminRoute?: string }) {
|
||||
return (
|
||||
<a className="nav__link" href={`${adminRoute.replace(/\/$/, '')}/stats`} id="nav-ipal-stats">
|
||||
<span className="nav__link-label">Statistics</span>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
export default StatsNavLink
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { AdminViewServerProps } from 'payload'
|
||||
|
||||
import { DefaultTemplate } from '@payloadcms/next/templates'
|
||||
import { Gutter } from '@payloadcms/ui'
|
||||
|
||||
import type { StatsVisit } from '../collection.js'
|
||||
|
||||
import { isAdmin } from '../../access/predicates.js'
|
||||
import { VISITOR_ID_PATTERN } from '../parse.js'
|
||||
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
|
||||
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
|
||||
|
||||
type Props = { adminRoute?: string; timeZone?: string } & AdminViewServerProps
|
||||
|
||||
const fmt = (n: number) => n.toLocaleString('en-US')
|
||||
const when = (iso: string, timeZone: string) =>
|
||||
new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso))
|
||||
|
||||
function TopList({ rows, title, unit }: { rows: [string, number][]; title: string; unit: string }) {
|
||||
return (
|
||||
<section>
|
||||
<h3>{title}</h3>
|
||||
{rows.length ? (
|
||||
<table className="ipal-stats-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{title}</th>
|
||||
<th scope="col">{unit}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(([key, count]) => (
|
||||
<tr key={key}>
|
||||
<td><code>{key}</code></td>
|
||||
<td>{fmt(count)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<p>No data yet.</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
|
||||
return (
|
||||
<>
|
||||
<p><a href={base}>← All statistics</a></p>
|
||||
<h1>Visitor <code>{visitorId}</code></h1>
|
||||
<p>
|
||||
{visits.length} visit{visits.length === 1 ? '' : 's'} recorded with analytics consent. To erase this
|
||||
visitor’s data, filter <em>Statistics → Visits</em> by this visitor id and delete the results.
|
||||
</p>
|
||||
{visits.map((v) => (
|
||||
<section className="ipal-stats-tile" key={v.id} style={{ marginBottom: '1rem' }}>
|
||||
<strong>{when(v.startedAt, timeZone)}</strong>
|
||||
<span>
|
||||
{' '}· {v.pageCount} page{v.pageCount === 1 ? '' : 's'} · {v.device ?? 'unknown device'}
|
||||
{v.referrer ? ` · from ${v.referrer}` : ''}
|
||||
</span>
|
||||
<ol style={{ margin: '0.5rem 0 0', paddingLeft: '1.25rem' }}>
|
||||
{(v.pages ?? []).map((p, i) => (
|
||||
<li key={`${p.t}-${i}`}>
|
||||
<code>{p.p}</code> <span>{when(p.t, timeZone).split(', ').pop()}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the
|
||||
* last 30 days, top pages, entry pages, referrers, devices, and — for visitors
|
||||
* who accepted analytics cookies — a per-visitor history (?visitor=<id>).
|
||||
* Admins only.
|
||||
*/
|
||||
export async function StatsView(props: Props) {
|
||||
const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props
|
||||
const { req, visibleEntities } = initPageResult
|
||||
const base = `${adminRoute.replace(/\/$/, '')}/stats`
|
||||
|
||||
const visitorParam = typeof searchParams?.visitor === 'string' ? searchParams.visitor : undefined
|
||||
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
|
||||
|
||||
let content: React.ReactNode
|
||||
if (!isAdmin(req.user)) {
|
||||
content = <p>Statistics are available to administrators only.</p>
|
||||
} else if (visitorId) {
|
||||
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
|
||||
} else {
|
||||
const [stats, recent] = await Promise.all([loadStats(req.payload, { timeZone }), loadRecentVisitors(req.payload, 50)])
|
||||
const { totals } = stats
|
||||
const visitors = [...new Map(recent.map((v) => [v.visitorId!, v])).values()].slice(0, 15)
|
||||
content = (
|
||||
<>
|
||||
<h1>Statistics</h1>
|
||||
<p>
|
||||
Last 30 days. Counted without cookies, so no consent is needed; no IP addresses are stored. Visitors who accept
|
||||
analytics cookies also get a history across days.
|
||||
</p>
|
||||
<div className="ipal-stats-tiles">
|
||||
<div className="ipal-stats-tile"><b>{fmt(totals.visits)}</b><span>Visits</span></div>
|
||||
<div className="ipal-stats-tile"><b>{fmt(totals.views)}</b><span>Page views</span></div>
|
||||
<div className="ipal-stats-tile">
|
||||
<b>{totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}</b><span>Pages per visit</span>
|
||||
</div>
|
||||
<div className="ipal-stats-tile"><b>{Math.round(totals.bounceRate * 100)}%</b><span>Single-page visits</span></div>
|
||||
<div className="ipal-stats-tile"><b>{fmt(totals.consented)}</b><span>Visits with analytics consent</span></div>
|
||||
</div>
|
||||
<h2>Visits per day</h2>
|
||||
<VisitsChart days={stats.days} />
|
||||
<div className="ipal-stats-lists">
|
||||
<TopList rows={stats.topPages} title="Page" unit="Views" />
|
||||
<TopList rows={stats.entries} title="Entry page" unit="Visits" />
|
||||
<TopList rows={stats.referrers} title="Referrer" unit="Visits" />
|
||||
<TopList rows={stats.devices} title="Device" unit="Visits" />
|
||||
</div>
|
||||
<section style={{ marginTop: '2rem' }}>
|
||||
<h3>Visitor history (analytics consent only)</h3>
|
||||
{visitors.length ? (
|
||||
<table className="ipal-stats-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Visitor</th>
|
||||
<th scope="col">Last seen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visitors.map((v) => (
|
||||
<tr key={v.visitorId}>
|
||||
<td><a aria-label={`Visitor ${v.visitorId}`} href={`${base}?visitor=${v.visitorId}`}><code>{v.visitorId}</code></a></td>
|
||||
<td>{when(v.lastAt, timeZone)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<p>No visitor has accepted analytics cookies yet.</p>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DefaultTemplate
|
||||
i18n={req.i18n}
|
||||
locale={initPageResult.locale}
|
||||
params={props.params}
|
||||
payload={req.payload}
|
||||
permissions={initPageResult.permissions}
|
||||
req={req}
|
||||
searchParams={searchParams}
|
||||
user={req.user ?? undefined}
|
||||
visibleEntities={visibleEntities}
|
||||
>
|
||||
<Gutter>
|
||||
<div className="ipal-stats" style={{ paddingBottom: '3rem' }}>
|
||||
<style>{STATS_CSS}</style>
|
||||
{content}
|
||||
</div>
|
||||
</Gutter>
|
||||
</DefaultTemplate>
|
||||
)
|
||||
}
|
||||
|
||||
export default StatsView
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { Payload, PayloadRequest } from 'payload'
|
||||
|
||||
import { isAdmin } from '../../access/predicates.js'
|
||||
import { loadStats } from './loadStats.js'
|
||||
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
|
||||
|
||||
type Props = {
|
||||
adminRoute?: string
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload
|
||||
req?: PayloadRequest
|
||||
timeZone?: string
|
||||
user?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard card (admin.components.beforeDashboard): visits per day for the
|
||||
* last 30 days with a link to the full view. Admins only; renders nothing on
|
||||
* any error (DB not ready, collection missing).
|
||||
*/
|
||||
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
|
||||
if (!payload || !isAdmin((req?.user ?? user) as never)) {return null}
|
||||
let stats
|
||||
try {
|
||||
stats = await loadStats(payload, { timeZone })
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<section className="ipal-stats" style={{ marginBottom: '2rem' }}>
|
||||
<style>{STATS_CSS}</style>
|
||||
<h2 style={{ marginBottom: '0.25rem' }}>Visits per day</h2>
|
||||
<p style={{ color: 'var(--theme-elevation-500)', margin: '0 0 0.75rem' }}>
|
||||
Last 30 days: {stats.totals.visits.toLocaleString('en-US')} visits, {stats.totals.views.toLocaleString('en-US')} page views ·{' '}
|
||||
<a href={`${adminRoute.replace(/\/$/, '')}/stats`}>All statistics →</a>
|
||||
</p>
|
||||
<VisitsChart days={stats.days} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export default StatsWidget
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { StatsDay } from '../summarize.js'
|
||||
|
||||
const W = 1000
|
||||
const H = 220
|
||||
const PAD = { bottom: 24, left: 36, right: 8, top: 12 }
|
||||
const RADIUS = 4
|
||||
|
||||
/** Round up to 1 / 2 / 5 × 10^k, so the gridlines land on readable numbers. */
|
||||
function niceMax(value: number): number {
|
||||
if (value <= 4) {return 4}
|
||||
const pow = 10 ** Math.floor(Math.log10(value))
|
||||
return ([1, 2, 5, 10].map((s) => s * pow).find((s) => s >= value) ?? 10 * pow)
|
||||
}
|
||||
|
||||
/** Column with a 4px rounded top and a square base on the baseline. */
|
||||
function column(x: number, y: number, w: number, h: number): string {
|
||||
const r = Math.min(RADIUS, w / 2, h)
|
||||
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`
|
||||
}
|
||||
|
||||
const shortDate = (day: string) => `${day.slice(8, 10)}.${day.slice(5, 7)}`
|
||||
|
||||
/**
|
||||
* Visits per day — server-rendered SVG, no client JS. One series, so no
|
||||
* legend: the heading names it. Each day has a full-height hover target with
|
||||
* a native tooltip, and the numbers are in a table below for screen readers.
|
||||
*/
|
||||
export function VisitsChart({ days }: { days: StatsDay[] }) {
|
||||
const max = niceMax(Math.max(0, ...days.map((d) => d.visits)))
|
||||
const plotW = W - PAD.left - PAD.right
|
||||
const plotH = H - PAD.top - PAD.bottom
|
||||
const band = plotW / Math.max(1, days.length)
|
||||
const barW = Math.min(24, band - 2)
|
||||
const y = (v: number) => PAD.top + plotH - (v / max) * plotH
|
||||
const ticks = [0, max / 2, max]
|
||||
|
||||
return (
|
||||
<figure className="ipal-stats-chart" style={{ margin: 0 }}>
|
||||
<svg aria-hidden="true" style={{ display: 'block', height: 'auto', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
|
||||
{ticks.map((t) => (
|
||||
<g key={t}>
|
||||
<line className="ipal-stats-grid" x1={PAD.left} x2={W - PAD.right} y1={y(t)} y2={y(t)} />
|
||||
<text className="ipal-stats-axis" dominantBaseline="middle" textAnchor="end" x={PAD.left - 6} y={y(t)}>
|
||||
{Number.isInteger(t) ? t : t.toFixed(1)}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{days.map((d, i) => {
|
||||
const x = PAD.left + i * band
|
||||
const h = (d.visits / max) * plotH
|
||||
const label = i % 7 === (days.length - 1) % 7
|
||||
return (
|
||||
<g className="ipal-stats-day" key={d.day}>
|
||||
<title>{`${d.day}: ${d.visits} visits, ${d.views} page views`}</title>
|
||||
<rect fill="transparent" height={plotH} width={band} x={x} y={PAD.top} />
|
||||
{h > 0 ? <path className="ipal-stats-bar" d={column(x + (band - barW) / 2, y(d.visits), barW, h)} /> : null}
|
||||
{label ? (
|
||||
<text className="ipal-stats-axis" textAnchor="middle" x={x + band / 2} y={H - 6}>
|
||||
{shortDate(d.day)}
|
||||
</text>
|
||||
) : null}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
<details style={{ marginTop: '0.5rem' }}>
|
||||
<summary>Table</summary>
|
||||
<table className="ipal-stats-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Day</th>
|
||||
<th scope="col">Visits</th>
|
||||
<th scope="col">Page views</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...days].reverse().map((d) => (
|
||||
<tr key={d.day}>
|
||||
<td>{d.day}</td>
|
||||
<td>{d.visits}</td>
|
||||
<td>{d.views}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
</figure>
|
||||
)
|
||||
}
|
||||
|
||||
/** Colors from the reference palette (series 1, light/dark) + Payload's theme tokens for ink. */
|
||||
export const STATS_CSS = `
|
||||
.ipal-stats { --ipal-series-1: #2a78d6; }
|
||||
html[data-theme='dark'] .ipal-stats { --ipal-series-1: #3987e5; }
|
||||
.ipal-stats-bar { fill: var(--ipal-series-1); }
|
||||
.ipal-stats-day:hover .ipal-stats-bar { opacity: 0.8; }
|
||||
.ipal-stats-grid { stroke: var(--theme-elevation-100); stroke-width: 1; }
|
||||
.ipal-stats-axis { fill: var(--theme-elevation-500); font-size: 11px; }
|
||||
.ipal-stats-tiles { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 1rem 0 1.5rem; }
|
||||
.ipal-stats-tile { border: 1px solid var(--theme-elevation-150); border-radius: 4px; padding: 0.75rem 1rem; }
|
||||
.ipal-stats-tile b { display: block; font-size: 1.75rem; line-height: 1.2; }
|
||||
.ipal-stats-tile span { color: var(--theme-elevation-500); font-size: 0.85rem; }
|
||||
.ipal-stats-lists { display: grid; gap: 1.5rem; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); margin-top: 2rem; }
|
||||
.ipal-stats-table { border-collapse: collapse; width: 100%; }
|
||||
.ipal-stats-table th, .ipal-stats-table td { border-bottom: 1px solid var(--theme-elevation-100); padding: 0.35rem 0.5rem; text-align: left; }
|
||||
.ipal-stats-table td:not(:first-child), .ipal-stats-table th:not(:first-child) { font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.ipal-stats-table code { word-break: break-all; }
|
||||
`
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import type { StatsVisit } from '../collection.js'
|
||||
import type { StatsSummary } from '../summarize.js'
|
||||
|
||||
import { STATS_SLUG } from '../collection.js'
|
||||
import { lastDays, summarize } from '../summarize.js'
|
||||
|
||||
const VISIT_FIELDS = {
|
||||
day: true,
|
||||
device: true,
|
||||
entry: true,
|
||||
exit: true,
|
||||
lastAt: true,
|
||||
pageCount: true,
|
||||
pages: true,
|
||||
referrer: true,
|
||||
startedAt: true,
|
||||
visitorId: true,
|
||||
} as const
|
||||
|
||||
/** Summary of the last `days` days. Callers check the user is an admin first. */
|
||||
export async function loadStats(payload: Payload, { days = 30, timeZone = 'Europe/Warsaw' } = {}): Promise<StatsSummary> {
|
||||
const range = lastDays(days, timeZone)
|
||||
const { docs } = await payload.find({
|
||||
collection: STATS_SLUG as never,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
pagination: false,
|
||||
select: VISIT_FIELDS as never,
|
||||
where: { day: { greater_than_equal: range[0] } },
|
||||
})
|
||||
return summarize(docs as unknown as StatsVisit[], range)
|
||||
}
|
||||
|
||||
/** Every stored visit of one consenting visitor, newest first. */
|
||||
export async function loadVisitor(payload: Payload, visitorId: string): Promise<StatsVisit[]> {
|
||||
const { docs } = await payload.find({
|
||||
collection: STATS_SLUG as never,
|
||||
depth: 0,
|
||||
limit: 500,
|
||||
overrideAccess: true,
|
||||
pagination: false,
|
||||
select: VISIT_FIELDS as never,
|
||||
sort: '-startedAt',
|
||||
where: { visitorId: { equals: visitorId } },
|
||||
})
|
||||
return docs as unknown as StatsVisit[]
|
||||
}
|
||||
|
||||
/** Latest visits that carry a visitor id — the entry points into visitor history. */
|
||||
export async function loadRecentVisitors(payload: Payload, limit = 20): Promise<StatsVisit[]> {
|
||||
const { docs } = await payload.find({
|
||||
collection: STATS_SLUG as never,
|
||||
depth: 0,
|
||||
limit,
|
||||
overrideAccess: true,
|
||||
select: VISIT_FIELDS as never,
|
||||
sort: '-lastAt',
|
||||
where: { visitorId: { exists: true } },
|
||||
})
|
||||
return docs as unknown as StatsVisit[]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
'use client'
|
||||
export { PageStats, VISITOR_COOKIE } from './PageStats.js'
|
||||
export type { PageStatsProps } from './PageStats.js'
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { isAdmin } from '../access/predicates.js'
|
||||
|
||||
/**
|
||||
* One document per visit (a run of page views with gaps under 30 minutes).
|
||||
*
|
||||
* Without consent a visit is anonymous: `visitKey` is a daily-salted hash
|
||||
* (visitKey.ts) that can't be traced back to an IP or linked across days.
|
||||
* With analytics consent the visit also carries `visitorId` — the random id
|
||||
* from the visitor's `ipal_vid` cookie — and the panel can show that visitor's
|
||||
* history across days. No IP, no user agent, no query strings are stored.
|
||||
*/
|
||||
|
||||
export const STATS_SLUG = 'stats-visits'
|
||||
|
||||
export type StatsOptions = {
|
||||
/** Show the 30-day chart on the admin dashboard. Default true. */
|
||||
dashboard?: boolean
|
||||
/** Days a visit is kept. Default 90 (the dashboard shows 30). */
|
||||
retentionDays?: number
|
||||
/** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */
|
||||
timeZone?: string
|
||||
}
|
||||
|
||||
export type StatsPage = { p: string; t: string }
|
||||
|
||||
export type StatsVisit = {
|
||||
country?: null | string
|
||||
day: string
|
||||
device?: 'desktop' | 'mobile' | 'tablet' | null
|
||||
entry: string
|
||||
exit: string
|
||||
id: number | string
|
||||
lastAt: string
|
||||
locale?: null | string
|
||||
pageCount: number
|
||||
pages?: null | StatsPage[]
|
||||
referrer?: null | string
|
||||
startedAt: string
|
||||
visitorId?: null | string
|
||||
}
|
||||
|
||||
export function buildStatsCollection(): CollectionConfig {
|
||||
return {
|
||||
slug: STATS_SLUG,
|
||||
access: {
|
||||
// Written only by the hit endpoint (Local API); read and deleted by admins
|
||||
// (deleting is how a visitor's erasure request is handled).
|
||||
create: () => false,
|
||||
delete: ({ req: { user } }) => isAdmin(user),
|
||||
read: ({ req: { user } }) => isAdmin(user),
|
||||
update: () => false,
|
||||
},
|
||||
admin: {
|
||||
defaultColumns: ['day', 'entry', 'pageCount', 'referrer', 'device', 'visitorId'],
|
||||
description:
|
||||
'Visits from the built-in statistics. Anonymous by default; a visitor id appears only for visitors who accepted analytics cookies. No IP addresses are stored.',
|
||||
group: 'Statistics',
|
||||
useAsTitle: 'entry',
|
||||
},
|
||||
fields: [
|
||||
{ name: 'day', type: 'text', index: true, required: true },
|
||||
{ name: 'startedAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, required: true },
|
||||
{ name: 'lastAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, index: true, required: true },
|
||||
{ name: 'entry', type: 'text', required: true },
|
||||
{ name: 'exit', type: 'text', required: true },
|
||||
{ name: 'pageCount', type: 'number', required: true },
|
||||
{ name: 'pages', type: 'json' },
|
||||
{ name: 'referrer', type: 'text' },
|
||||
{
|
||||
name: 'device',
|
||||
type: 'select',
|
||||
options: ['desktop', 'mobile', 'tablet'],
|
||||
},
|
||||
{ name: 'locale', type: 'text' },
|
||||
{ name: 'country', type: 'text' },
|
||||
{
|
||||
name: 'visitorId',
|
||||
type: 'text',
|
||||
admin: { description: 'Only with analytics consent — the id from the visitor’s ipal_vid cookie.' },
|
||||
index: true,
|
||||
},
|
||||
// Daily-salted, unlinkable after midnight; only used to join hits into a visit.
|
||||
{ name: 'visitKey', type: 'text', admin: { hidden: true }, index: true },
|
||||
],
|
||||
labels: { plural: 'Visits', singular: 'Visit' },
|
||||
timestamps: false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
|
||||
|
||||
import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js'
|
||||
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
|
||||
import { STATS_SLUG } from './collection.js'
|
||||
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
|
||||
import { visitKey } from './visitKey.js'
|
||||
|
||||
const VISIT_GAP_MS = 30 * 60 * 1000
|
||||
const MAX_PAGES = 200
|
||||
|
||||
let lastPurge = 0
|
||||
let policy: { at: number; version: number } | null = null
|
||||
|
||||
/** Cookie Settings → Policy version, cached for a minute (read on every hit). */
|
||||
async function policyVersion(req: PayloadRequest): Promise<number> {
|
||||
if (policy && Date.now() - policy.at < 60_000) {return policy.version}
|
||||
let version = CONSENT_VERSION
|
||||
try {
|
||||
const g = (await req.payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0 })) as { policyVersion?: unknown }
|
||||
if (typeof g.policyVersion === 'number' && g.policyVersion >= 1) {version = Math.trunc(g.policyVersion)}
|
||||
} catch {
|
||||
// global missing — the default version applies
|
||||
}
|
||||
policy = { at: Date.now(), version }
|
||||
return version
|
||||
}
|
||||
|
||||
function readCookie(header: null | string, name: string): string | undefined {
|
||||
return header
|
||||
?.split(/;\s*/)
|
||||
.find((c) => c.startsWith(`${name}=`))
|
||||
?.slice(name.length + 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/ipal/hit — one page view, sent by <PageStats>. Body:
|
||||
* `{ p: path, r?: referrer, l?: locale, v?: visitor id }`.
|
||||
*
|
||||
* Always 204 (nothing for a script to learn). The visitor id is kept only when
|
||||
* the request's own consent cookie grants analytics under the current policy
|
||||
* version — the server checks, it doesn't take the browser's word for it.
|
||||
* Logged-in panel users, bots and prefetches aren't counted.
|
||||
*/
|
||||
export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint {
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const done = new Response(null, { status: 204 })
|
||||
const request = req as unknown as Request
|
||||
const headers = request.headers
|
||||
const ip = clientIp(request)
|
||||
|
||||
const limit = await consumeRateLimit({ key: ip, max: 60, scope: 'stats' })
|
||||
if (!limit.ok) {return done}
|
||||
|
||||
const ua = headers.get('user-agent') ?? ''
|
||||
if (isBot(ua) || req.user) {return done}
|
||||
if (/prefetch|prerender/i.test(headers.get('sec-purpose') ?? headers.get('purpose') ?? '')) {return done}
|
||||
|
||||
let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown }
|
||||
try {
|
||||
body = (await request.json()) as typeof body
|
||||
} catch {
|
||||
return done
|
||||
}
|
||||
const path = sanitizePath(body?.p)
|
||||
if (!path) {return done}
|
||||
|
||||
const host = headers.get('host') ?? ''
|
||||
let visitorId: string | undefined
|
||||
if (typeof body.v === 'string' && VISITOR_ID_PATTERN.test(body.v)) {
|
||||
const consent = parseConsent(readCookie(headers.get('cookie'), CONSENT_COOKIE), await policyVersion(req))
|
||||
if (consent?.analytics) {visitorId = body.v}
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
const day = dayOf(now, timeZone)
|
||||
const key = visitKey(day, [ip, ua, host])
|
||||
|
||||
try {
|
||||
const { docs } = await req.payload.find({
|
||||
collection: STATS_SLUG as never,
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
pagination: false,
|
||||
sort: '-lastAt',
|
||||
where: {
|
||||
and: [
|
||||
{ visitKey: { equals: key } },
|
||||
{ lastAt: { greater_than: new Date(now.getTime() - VISIT_GAP_MS).toISOString() } },
|
||||
],
|
||||
},
|
||||
})
|
||||
const visit = docs[0] as StatsVisit | undefined
|
||||
|
||||
if (visit) {
|
||||
const pages: StatsPage[] = Array.isArray(visit.pages) ? visit.pages : []
|
||||
const last = pages[pages.length - 1]
|
||||
// a reload within 10 s isn't a new page view
|
||||
const reload = last?.p === path && now.getTime() - Date.parse(last.t) < 10_000
|
||||
if (!reload && pages.length < MAX_PAGES) {pages.push({ p: path, t: now.toISOString() })}
|
||||
await req.payload.update({
|
||||
id: visit.id,
|
||||
collection: STATS_SLUG as never,
|
||||
data: {
|
||||
exit: path,
|
||||
lastAt: now.toISOString(),
|
||||
pageCount: pages.length,
|
||||
pages,
|
||||
...(visitorId && !visit.visitorId ? { visitorId } : {}),
|
||||
} as never,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
} else {
|
||||
const country = headers.get('cf-ipcountry')
|
||||
await req.payload.create({
|
||||
collection: STATS_SLUG as never,
|
||||
data: {
|
||||
day,
|
||||
device: deviceFromUa(ua),
|
||||
entry: path,
|
||||
exit: path,
|
||||
lastAt: now.toISOString(),
|
||||
pageCount: 1,
|
||||
pages: [{ p: path, t: now.toISOString() }],
|
||||
referrer: referrerHost(body.r, host),
|
||||
startedAt: now.toISOString(),
|
||||
visitKey: key,
|
||||
...(typeof body.l === 'string' && /^[a-z]{2}(?:-[A-Za-z]{2})?$/.test(body.l) ? { locale: body.l } : {}),
|
||||
...(country && /^[A-Z]{2}$/.test(country) && country !== 'XX' ? { country } : {}),
|
||||
...(visitorId ? { visitorId } : {}),
|
||||
} as never,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (now.getTime() - lastPurge > 24 * 60 * 60 * 1000) {
|
||||
lastPurge = now.getTime()
|
||||
await req.payload.delete({
|
||||
collection: STATS_SLUG as never,
|
||||
overrideAccess: true,
|
||||
where: { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } },
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
return done
|
||||
},
|
||||
method: 'post',
|
||||
path: '/ipal/hit',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Server-safe: collection + hit endpoint (wired by ipalKit({ stats })). <PageStats>
|
||||
// is client-side (./client); the admin view and dashboard card are in /admin.
|
||||
export { buildStatsCollection, STATS_SLUG } from './collection.js'
|
||||
export type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
|
||||
export { buildStatsEndpoint } from './endpoint.js'
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Request → clean, non-identifying fields for a stats hit. Pure functions, so
|
||||
* they're testable and run the same on every runtime.
|
||||
*/
|
||||
|
||||
export type Device = 'desktop' | 'mobile' | 'tablet'
|
||||
|
||||
/** Crawlers, link previews, headless browsers, uptime checks — not visitors. */
|
||||
const BOT_UA =
|
||||
/bot|crawl|spider|slurp|facebookexternalhit|embedly|preview|headless|lighthouse|pagespeed|pingdom|uptime|monitor|curl|wget|python|axios|node-fetch|go-http|java\//i
|
||||
|
||||
export function isBot(userAgent: string): boolean {
|
||||
return !userAgent || BOT_UA.test(userAgent)
|
||||
}
|
||||
|
||||
/** Coarse device class — never the model, OS version or browser build. */
|
||||
export function deviceFromUa(userAgent: string): Device {
|
||||
if (/ipad|tablet|android(?!.*mobile)/i.test(userAgent)) {return 'tablet'}
|
||||
if (/mobi|iphone|ipod|android/i.test(userAgent)) {return 'mobile'}
|
||||
return 'desktop'
|
||||
}
|
||||
|
||||
/**
|
||||
* Path only: query and hash dropped — they can carry e-mails, tokens, search
|
||||
* terms. Null for anything that isn't a same-site path.
|
||||
*/
|
||||
export function sanitizePath(value: unknown): null | string {
|
||||
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) {return null}
|
||||
const path = value.split(/[?#]/)[0].slice(0, 300)
|
||||
return /^[^\s<>"]*$/.test(path) ? path : null
|
||||
}
|
||||
|
||||
/** Referrer reduced to its hostname; empty for internal navigation or garbage. */
|
||||
export function referrerHost(value: unknown, ownHost: string): string {
|
||||
if (typeof value !== 'string' || !value) {return ''}
|
||||
try {
|
||||
const host = new URL(value).hostname.replace(/^www\./, '')
|
||||
return host && host !== ownHost.replace(/^www\./, '').split(':')[0] ? host.slice(0, 100) : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Visitor id stored in the `ipal_vid` cookie — only ever set after analytics consent. */
|
||||
export const VISITOR_ID_PATTERN = /^[0-9a-f]{32}$/
|
||||
|
||||
/** Calendar day in `timeZone`, 'YYYY-MM-DD' — the site's day, not the server's. */
|
||||
export function dayOf(date: Date, timeZone = 'UTC'): string {
|
||||
return new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', timeZone, year: 'numeric' }).format(date)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { StatsVisit } from './collection.js'
|
||||
|
||||
import { dayOf } from './parse.js'
|
||||
|
||||
export type StatsDay = { day: string; views: number; visits: number }
|
||||
|
||||
export type StatsSummary = {
|
||||
/** Oldest first, one entry per day — days without visits are zeros. */
|
||||
days: StatsDay[]
|
||||
devices: [string, number][]
|
||||
entries: [string, number][]
|
||||
referrers: [string, number][]
|
||||
topPages: [string, number][]
|
||||
totals: {
|
||||
/** Share of visits with a single page view, 0–1. */
|
||||
bounceRate: number
|
||||
/** Visits that carry a visitor id (analytics consent given). */
|
||||
consented: number
|
||||
views: number
|
||||
visits: number
|
||||
}
|
||||
}
|
||||
|
||||
/** The last `count` calendar days in `timeZone`, oldest first. */
|
||||
export function lastDays(count: number, timeZone: string, now = new Date()): string[] {
|
||||
// today in the site's zone, then plain calendar arithmetic — DST can't skip or repeat a day
|
||||
const [y, m, d] = dayOf(now, timeZone).split('-').map(Number)
|
||||
const today = Date.UTC(y, m - 1, d)
|
||||
return Array.from({ length: count }, (_, i) => new Date(today - (count - 1 - i) * 86_400_000).toISOString().slice(0, 10))
|
||||
}
|
||||
|
||||
function top(counts: Map<string, number>, limit: number): [string, number][] {
|
||||
return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, limit)
|
||||
}
|
||||
|
||||
function bump(map: Map<string, number>, key: string, by = 1) {
|
||||
map.set(key, (map.get(key) ?? 0) + by)
|
||||
}
|
||||
|
||||
/** Daily series and top lists from raw visits. */
|
||||
export function summarize(visits: StatsVisit[], days: string[], limit = 10): StatsSummary {
|
||||
const byDay = new Map(days.map((d) => [d, { day: d, views: 0, visits: 0 }]))
|
||||
const pages = new Map<string, number>()
|
||||
const entries = new Map<string, number>()
|
||||
const referrers = new Map<string, number>()
|
||||
const devices = new Map<string, number>()
|
||||
let views = 0
|
||||
let bounces = 0
|
||||
let consented = 0
|
||||
let counted = 0
|
||||
|
||||
for (const visit of visits) {
|
||||
const bucket = byDay.get(visit.day)
|
||||
if (!bucket) {continue}
|
||||
counted++
|
||||
bucket.visits++
|
||||
bucket.views += visit.pageCount
|
||||
views += visit.pageCount
|
||||
if (visit.pageCount <= 1) {bounces++}
|
||||
if (visit.visitorId) {consented++}
|
||||
for (const page of visit.pages ?? []) {bump(pages, page.p)}
|
||||
bump(entries, visit.entry)
|
||||
bump(referrers, visit.referrer || '(direct)')
|
||||
if (visit.device) {bump(devices, visit.device)}
|
||||
}
|
||||
|
||||
return {
|
||||
days: [...byDay.values()],
|
||||
devices: top(devices, limit),
|
||||
entries: top(entries, limit),
|
||||
referrers: top(referrers, limit),
|
||||
topPages: top(pages, limit),
|
||||
totals: { bounceRate: counted ? bounces / counted : 0, consented, views, visits: counted },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* Cookieless visit key: SHA-256 of a random salt + IP + user agent + host. The
|
||||
* salt lives only in this process's memory and is replaced when the day
|
||||
* changes — the old one is gone, so nobody (us included) can link a stored key
|
||||
* back to an IP or to the same visitor on another day. Nothing is stored on
|
||||
* the visitor's device, which is why this needs no consent.
|
||||
*
|
||||
* Trade-off: a restart or a second instance starts its own salt, so a visit in
|
||||
* progress can split in two. Fine for statistics; never fixed by persisting the
|
||||
* salt — that would make yesterday's keys reversible.
|
||||
*/
|
||||
let current: { day: string; salt: Buffer } | null = null
|
||||
|
||||
export function visitKey(day: string, parts: string[]): string {
|
||||
if (!current || current.day !== day) {current = { day, salt: randomBytes(32) }}
|
||||
return createHash('sha256').update(current.salt).update(parts.join('\n')).digest('hex').slice(0, 32)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
|
||||
|
||||
export type ImagesConfig = {
|
||||
/** Development only: lets next/image optimize files served by the app itself on localhost. */
|
||||
dangerouslyAllowLocalIP?: boolean
|
||||
formats: ('image/avif' | 'image/webp')[]
|
||||
minimumCacheTTL: number
|
||||
remotePatterns: RemotePattern[]
|
||||
@@ -11,15 +13,20 @@ export type ImagesConfig = {
|
||||
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality;
|
||||
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
|
||||
* optimize R2 files — otherwise it refuses them;
|
||||
* - optimized images cached for 31 days (uploads get new names when replaced).
|
||||
* - optimized images cached for 31 days (uploads get new names when replaced);
|
||||
* - outside production, media served by the app itself (`/api/media/file/**` on
|
||||
* NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which
|
||||
* Next 16 otherwise refuses as a private IP.
|
||||
*
|
||||
* import { buildImagesConfig } from '@intecion/ipal-kit'
|
||||
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
|
||||
*/
|
||||
export function buildImagesConfig({
|
||||
extraHosts = [],
|
||||
production = process.env.NODE_ENV === 'production',
|
||||
publicUrl = process.env.R2_PUBLIC_URL,
|
||||
}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig {
|
||||
serverUrl = process.env.NEXT_PUBLIC_SERVER_URL,
|
||||
}: { extraHosts?: string[]; production?: boolean; publicUrl?: string; serverUrl?: string } = {}): ImagesConfig {
|
||||
const remotePatterns: RemotePattern[] = []
|
||||
if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
|
||||
const u = new URL(publicUrl)
|
||||
@@ -31,5 +38,21 @@ export function buildImagesConfig({
|
||||
})
|
||||
}
|
||||
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
|
||||
return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns }
|
||||
let localMedia = false
|
||||
if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) {
|
||||
const u = new URL(serverUrl)
|
||||
remotePatterns.push({
|
||||
hostname: u.hostname,
|
||||
protocol: u.protocol.replace(':', '') as 'http' | 'https',
|
||||
...(u.port ? { port: u.port } : {}),
|
||||
pathname: '/api/media/file/**',
|
||||
})
|
||||
localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
|
||||
}
|
||||
return {
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
minimumCacheTTL: 60 * 60 * 24 * 31,
|
||||
remotePatterns,
|
||||
...(localMedia ? { dangerouslyAllowLocalIP: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { Plugin } from 'payload'
|
||||
import type { CollectionConfig, Plugin } from 'payload'
|
||||
|
||||
import { APIError } from 'payload'
|
||||
|
||||
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
|
||||
|
||||
@@ -16,6 +18,8 @@ export type S3StorageFactory = (options: {
|
||||
forcePathStyle: boolean
|
||||
region: string
|
||||
}
|
||||
/** false = registered but inactive: no S3 client, local disk, admin import map unchanged. */
|
||||
enabled?: boolean
|
||||
}) => Plugin
|
||||
|
||||
export type BuildR2StorageDeps = {
|
||||
@@ -58,17 +62,43 @@ export const buildR2Storage = (
|
||||
const accessKeyId = process.env.R2_ACCESS_KEY_ID
|
||||
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY
|
||||
|
||||
// Any missing → skip R2, fall back to local disk. Warn so it's not silent.
|
||||
const { s3Storage } = deps
|
||||
|
||||
// Any missing → local disk. The adapter is still REGISTERED (enabled: false) when the
|
||||
// project injects it: storage-s3 adds its admin client handler to the import map even
|
||||
// when disabled, so `pnpm dev` / `generate:importmap` without R2 env writes the same
|
||||
// importMap.js as production. Before 1.12.2 a no-op was returned here — an import map
|
||||
// generated in dev lacked S3ClientUploadHandler and the production admin rendered blank.
|
||||
if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {
|
||||
const readOnly = readOnlyPublicUrl({ accessKeyId, bucket, endpoint, secretAccessKey })
|
||||
const disabled: Plugin | undefined = s3Storage
|
||||
? s3Storage({
|
||||
bucket: bucket ?? '',
|
||||
collections: Object.fromEntries(collections.map((slug) => [slug, true as const])),
|
||||
config: {
|
||||
credentials: { accessKeyId: accessKeyId ?? '', secretAccessKey: secretAccessKey ?? '' },
|
||||
endpoint: endpoint ?? '',
|
||||
forcePathStyle: true,
|
||||
region: 'auto',
|
||||
},
|
||||
enabled: false,
|
||||
})
|
||||
: undefined
|
||||
return (config) => {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
if (readOnly) {
|
||||
console.warn(
|
||||
`[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` +
|
||||
'uploads are disabled. Set all R2_* to upload, or none for local disk.',
|
||||
)
|
||||
} else if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
console.warn(
|
||||
'[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +
|
||||
'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',
|
||||
)
|
||||
}
|
||||
return config
|
||||
const next = disabled ? disabled(config) : config
|
||||
return readOnly ? withReadOnlyMedia(next as Parameters<Plugin>[0], collections, readOnly) : next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +125,6 @@ export const buildR2Storage = (
|
||||
|
||||
// R2 env is complete → the adapter is required. Fail loudly at boot rather
|
||||
// than silently storing media on the container disk (lost on redeploy).
|
||||
const { s3Storage } = deps
|
||||
if (!s3Storage) {
|
||||
throw new Error(
|
||||
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
|
||||
@@ -121,3 +150,76 @@ export const buildR2Storage = (
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only media: outside production, R2_PUBLIC_URL (absolute) with none of the
|
||||
* credentials → files are read from the public domain. For a local dev pointed at
|
||||
* a production database: images show, nothing can be uploaded to (or deleted from)
|
||||
* the real bucket. Returns the base URL, or null when the mode doesn't apply.
|
||||
*/
|
||||
function readOnlyPublicUrl(env: {
|
||||
accessKeyId?: string
|
||||
bucket?: string
|
||||
endpoint?: string
|
||||
secretAccessKey?: string
|
||||
}): null | string {
|
||||
if (process.env.NODE_ENV === 'production') {return null}
|
||||
if (env.accessKeyId || env.bucket || env.endpoint || env.secretAccessKey) {return null}
|
||||
const url = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '')
|
||||
return url && /^https?:\/\/[^/\s]+/i.test(url) ? url : null
|
||||
}
|
||||
|
||||
type UploadDoc = {
|
||||
filename?: null | string
|
||||
sizes?: Record<string, { filename?: null | string; url?: null | string } | null>
|
||||
thumbnailURL?: null | string
|
||||
url?: null | string
|
||||
}
|
||||
|
||||
function withReadOnlyMedia(
|
||||
config: Parameters<Plugin>[0],
|
||||
collections: string[],
|
||||
publicUrl: string,
|
||||
): Parameters<Plugin>[0] {
|
||||
const fileUrl = (filename: string) => `${publicUrl}/${encodeURIComponent(filename)}`
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection): CollectionConfig => {
|
||||
if (!collections.includes(collection.slug)) {return collection}
|
||||
return {
|
||||
...collection,
|
||||
hooks: {
|
||||
...collection.hooks,
|
||||
afterRead: [
|
||||
...(collection.hooks?.afterRead ?? []),
|
||||
({ doc }: { doc: UploadDoc }) => {
|
||||
if (!doc?.filename) {return doc}
|
||||
doc.url = fileUrl(doc.filename)
|
||||
if (doc.thumbnailURL) {
|
||||
const thumb = doc.sizes?.thumbnail?.filename
|
||||
doc.thumbnailURL = thumb ? fileUrl(thumb) : doc.url
|
||||
}
|
||||
for (const size of Object.values(doc.sizes ?? {})) {
|
||||
if (size?.filename) {size.url = fileUrl(size.filename)}
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
beforeOperation: [
|
||||
...(collection.hooks?.beforeOperation ?? []),
|
||||
({ args, operation }) => {
|
||||
const req = (args as { req?: { file?: unknown } }).req
|
||||
if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) {
|
||||
throw new APIError(
|
||||
'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
|
||||
403,
|
||||
)
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ThemeConfig } from './theme.js'
|
||||
|
||||
import { themeScript } from './theme.js'
|
||||
|
||||
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
|
||||
|
||||
/**
|
||||
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
|
||||
* theme. Put it first in <body> (or turn on `theme` in <SiteProviders>), and
|
||||
* add `suppressHydrationWarning` to <html>: the attribute differs from the server HTML on purpose.
|
||||
*
|
||||
* const shell = await getSiteShell(locale)
|
||||
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
|
||||
*/
|
||||
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
|
||||
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { Moon, Sun } from 'lucide-react'
|
||||
|
||||
import type { Theme } from './theme.js'
|
||||
|
||||
import { useTheme } from './useTheme.js'
|
||||
|
||||
export type ThemeSwitcherClassNames = {
|
||||
/** Wrapper of the dark icon. */
|
||||
dark?: string
|
||||
/** Wrapper of the light icon. */
|
||||
light?: string
|
||||
/** The <button>. */
|
||||
root?: string
|
||||
}
|
||||
|
||||
export type ThemeSwitcherProps = {
|
||||
classNames?: ThemeSwitcherClassNames
|
||||
/** Accessible name — Site Settings → Theme → Toggle label (shell.theme.toggleLabel). */
|
||||
label?: null | string
|
||||
/** Your icons. Default lucide Sun / Moon. `null` → no icon. */
|
||||
renderIcon?: (theme: Theme) => ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Light / dark switch with no styles: a <button role="switch"> (checked = dark)
|
||||
* holding a light and a dark icon. Which one looks active is CSS's job — from
|
||||
* the attribute on <html> (`[data-theme=dark] …`, Tailwind `dark:`), so the
|
||||
* server HTML is already right and nothing jumps after hydration.
|
||||
* Hooks: data-ipal="theme-switch", data-ipal-theme-icon="light|dark".
|
||||
*/
|
||||
export function ThemeSwitcher({ classNames: cn = {}, label, renderIcon }: ThemeSwitcherProps) {
|
||||
const { theme, toggle } = useTheme()
|
||||
const icon = (t: Theme) => (renderIcon ? renderIcon(t) : t === 'light' ? <Sun aria-hidden size="1.25em" /> : <Moon aria-hidden size="1.15em" />)
|
||||
return (
|
||||
<button
|
||||
aria-checked={theme === 'dark'}
|
||||
aria-label={label ?? undefined}
|
||||
className={cn.root}
|
||||
data-ipal="theme-switch"
|
||||
onClick={toggle}
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span className={cn.light} data-ipal-theme-icon="light">{icon('light')}</span>
|
||||
<span className={cn.dark} data-ipal-theme-icon="dark">{icon('dark')}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { isTheme, isThemeSetting, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE, themeConfigFrom, themeScript } from './theme.js'
|
||||
export type { Theme, ThemeConfig, ThemeSetting } from './theme.js'
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Light / dark theme — shared names and the pre-paint script. Pure: safe on the
|
||||
* server and in the browser.
|
||||
*
|
||||
* The theme never reaches the server HTML (pages are ISR/SSG, one HTML for
|
||||
* everyone): <ThemeScript> sets `data-theme` on <html> before the first paint,
|
||||
* from the visitor's choice (localStorage — an interface preference, no cookie,
|
||||
* no tracking, no consent needed) or Site Settings → Theme → Default theme.
|
||||
*/
|
||||
|
||||
export type Theme = 'dark' | 'light'
|
||||
/** Site Settings → Default theme. 'system' follows the device (prefers-color-scheme). */
|
||||
export type ThemeSetting = 'system' | Theme
|
||||
|
||||
/** localStorage key of the visitor's choice. */
|
||||
export const THEME_STORAGE_KEY = 'ipal-theme'
|
||||
/** Attribute on <html>: `[data-theme=dark]`, Tailwind `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`. */
|
||||
export const THEME_ATTRIBUTE = 'data-theme'
|
||||
/** Set on <html> for a moment while switching — for a colour transition only then (`[data-theme-switching] * { transition: … }`). */
|
||||
export const THEME_SWITCHING_ATTRIBUTE = 'data-theme-switching'
|
||||
|
||||
export const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark'
|
||||
export const isThemeSetting = (value: unknown): value is ThemeSetting => value === 'system' || isTheme(value)
|
||||
|
||||
/** Theme options from Site Settings — what getSiteShell(locale).theme holds. */
|
||||
export type ThemeConfig = {
|
||||
/** Visitors may switch (and their choice is remembered). */
|
||||
allowToggle: boolean
|
||||
/** null: no Site Settings — no attribute, the base (light) CSS applies. */
|
||||
defaultTheme: null | ThemeSetting
|
||||
/** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */
|
||||
toggleLabel: null | string
|
||||
}
|
||||
|
||||
/** Reads Theme options from a Site Settings document. */
|
||||
export function themeConfigFrom(settings: unknown): ThemeConfig {
|
||||
const s = (settings && typeof settings === 'object' ? settings : {}) as Record<string, unknown>
|
||||
const label = typeof s.themeToggleLabel === 'string' && s.themeToggleLabel.trim() ? s.themeToggleLabel.trim() : null
|
||||
return {
|
||||
allowToggle: s.allowThemeToggle === true,
|
||||
defaultTheme: isThemeSetting(s.defaultTheme) ? s.defaultTheme : null,
|
||||
toggleLabel: label,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The inline script for <ThemeScript>: stored choice (only when the toggle is
|
||||
* allowed) → default theme → for 'system' the device setting. Sets
|
||||
* `data-theme` and `color-scheme` (native controls, scrollbars) on <html>.
|
||||
*/
|
||||
export function themeScript({ allowToggle, defaultTheme }: Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>): string {
|
||||
const stored = allowToggle
|
||||
? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}`
|
||||
: ''
|
||||
return (
|
||||
`(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${stored}` +
|
||||
`if(t==='system')t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';` +
|
||||
`if(t==='light'||t==='dark'){d.setAttribute(${JSON.stringify(THEME_ATTRIBUTE)},t);d.style.colorScheme=t}})()`
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user