Admin panel in English and Polish, reworded per docs/dev/admin-ux.md

- admin-i18n module: AdminText { en, pl }, component texts under the ipal
  namespace (project translations win), en + pl admin languages when the
  project sets none (project's supportedLanguages wins)
- every plugin label, description, option, tab and group as { en, pl };
  explicit labels instead of auto-labels; sentence case; glossary terms
- visible renames (slugs, names, data unchanged): Cookie banner, Form
  messages, Privacy group, Search engines, Maintenance, Spam protection,
  E-mail sending, stats nav link Overview (hidden without access)
- Polish visitor defaults by page locale: cookie banner, form messages,
  validators, lightbox, accessibility widget; {field} uses the label
- fixes: e-mail status banner used Turnstile wording; developer words and
  env var names out of editor messages; stats numbers/dates in the admin
  language; test e-mail no longer says ipal-kit
- test/adminUx.test.ts: length limits, en + pl present, no developer words

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 15:46:25 +01:00
co-authored by Claude Opus 5.5
parent eeac33ed2f
commit 6b46bc0c14
108 changed files with 2806 additions and 981 deletions
+13 -5
View File
@@ -5,6 +5,12 @@ import type { Role } from './types.js'
import { isAdmin } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
const ROLE_LABELS: Record<Role, { en: string; pl: string }> = {
admin: { en: 'Administrator', pl: 'Administrator' },
editor: { en: 'Editor', pl: 'Redaktor' },
user: { en: 'User', pl: 'Użytkownik' },
}
/**
* Builds the fixed `roles` field the plugin injects into the auth collection.
*
@@ -32,7 +38,11 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
update: ({ req: { user } }) => isAdmin(user),
},
admin: {
description: 'Role hierarchy: admin > editor > user.',
description: {
en: 'Administrators manage everything; editors manage content.',
pl: 'Administrator zarządza wszystkim, redaktor — treścią.',
},
position: 'sidebar',
},
defaultValue: [defaultRole],
hasMany: true,
@@ -49,10 +59,8 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
},
}
: {}),
options: ROLE_HIERARCHY.map((role) => ({
label: role.charAt(0).toUpperCase() + role.slice(1),
value: role,
})),
label: { en: 'Roles', pl: 'Role' },
options: ROLE_HIERARCHY.map((role) => ({ label: ROLE_LABELS[role], value: role })),
required: true,
saveToJWT: true,
}
@@ -14,6 +14,10 @@ export type A11yTexts = {
contrastInverted?: string
grayscale?: string
lineHeight?: string
/** Switch state "off". */
off?: string
/** Switch state "on". */
on?: string
open?: string
readableFont?: string
reduceMotion?: string
@@ -24,25 +28,46 @@ export type A11yTexts = {
}
/**
* English defaults. The widget is end-user facing and multilingual projects run
* in many locales, so the plugin ships a neutral English baseline — NOT Polish.
* Localize by passing `texts` for the active locale (see the component doc).
* Default texts in English and Polish. `locale` picks the set (Polish for
* 'pl' / 'pl-PL', English for anything else); `texts` overrides any of them.
*/
const DEFAULT_TEXTS: Required<A11yTexts> = {
bigCursor: 'Large cursor',
close: 'Close',
contrast: 'Contrast',
contrastHigh: 'High',
contrastInverted: 'Inverted',
grayscale: 'Grayscale',
lineHeight: 'Line spacing',
open: 'Open accessibility panel',
readableFont: 'Readable font',
reduceMotion: 'Reduce motion',
reset: 'Reset',
textSize: 'Text size',
title: 'Accessibility',
underlineLinks: 'Underline links',
export const A11Y_DEFAULT_TEXTS: { en: Required<A11yTexts>; pl: Required<A11yTexts> } = {
en: {
bigCursor: 'Large cursor',
close: 'Close',
contrast: 'Contrast',
contrastHigh: 'High',
contrastInverted: 'Inverted',
grayscale: 'Grayscale',
lineHeight: 'Line spacing',
off: 'Off',
on: 'On',
open: 'Open accessibility panel',
readableFont: 'Readable font',
reduceMotion: 'Reduce motion',
reset: 'Reset',
textSize: 'Text size',
title: 'Accessibility',
underlineLinks: 'Underline links',
},
pl: {
bigCursor: 'Duży kursor',
close: 'Zamknij',
contrast: 'Kontrast',
contrastHigh: 'Wysoki',
contrastInverted: 'Odwrócony',
grayscale: 'Skala szarości',
lineHeight: 'Odstęp między wierszami',
off: 'Wył.',
on: 'Wł.',
open: 'Otwórz panel dostępności',
readableFont: 'Czytelna czcionka',
reduceMotion: 'Ogranicz animacje',
reset: 'Przywróć domyślne',
textSize: 'Rozmiar tekstu',
title: 'Dostępność',
underlineLinks: 'Podkreśl linki',
},
}
export type A11yClassNames = {
@@ -67,26 +92,25 @@ export type A11yClassNames = {
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*
* Labels default to English; localize per locale by passing `texts` for the
* active language. Keep the translations in the project (or a localized global)
* and pass the active locale's set — the plugin stays content-agnostic:
* Labels: pass the page's `locale` for the built-in English or Polish set;
* another language (or different wording) goes in `texts`, which wins key by key:
*
* const A11Y: Record<string, A11yTexts> = {
* pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … },
* de: { title: 'Barrierefreiheit', … },
* }
* <AccessibilityWidget texts={A11Y[locale]} classNames={…} />
* <AccessibilityWidget locale={locale} classNames={…} />
* <AccessibilityWidget locale={locale} texts={locale === 'de' ? { title: 'Barrierefreiheit', … } : undefined} />
*/
export function AccessibilityWidget({
classNames,
locale,
texts,
}: {
classNames?: A11yClassNames
/** Page language — picks the default texts (Polish for 'pl', else English). */
locale?: string
texts?: A11yTexts
}) {
const { reset, set, state } = useAccessibility()
const [open, setOpen] = useState(false)
const t = { ...DEFAULT_TEXTS, ...texts }
const t = { ...(locale?.toLowerCase().startsWith('pl') ? A11Y_DEFAULT_TEXTS.pl : A11Y_DEFAULT_TEXTS.en), ...texts }
const cn = classNames ?? {}
const toggle = <K extends keyof A11yState>(key: K) => set(key, !state[key] as A11yState[K])
@@ -179,7 +203,7 @@ export function AccessibilityWidget({
onClick={() => toggle(key)}
type="button"
>
{state[key] ? 'ON' : 'OFF'}
{state[key] ? t.on : t.off}
</button>
</div>
))}
+1 -1
View File
@@ -1,6 +1,6 @@
'use client'
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'
export { AccessibilityWidget } from './AccessibilityWidget.js'
export { A11Y_DEFAULT_TEXTS, AccessibilityWidget } from './AccessibilityWidget.js'
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'
export type { A11yState } from './state.js'
export { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js'
+1 -1
View File
@@ -1,5 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'
export { AccessibilityWidget } from './AccessibilityWidget.js'
export { A11Y_DEFAULT_TEXTS, AccessibilityWidget } from './AccessibilityWidget.js'
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'
export {
A11Y_COOKIE,
+32
View File
@@ -0,0 +1,32 @@
import type { Config } from 'payload'
import { en } from 'payload/i18n/en'
import { pl } from 'payload/i18n/pl'
import { deepMergeSimple } from 'payload/shared'
import { adminTexts } from './texts/index.js'
/**
* Admin languages and the plugin's component texts.
*
* - `i18n.supportedLanguages`: English and Polish when the project set none;
* a project's own list always wins.
* - `i18n.translations`: the plugin's texts under the `ipal` namespace, with the
* project's translations merged on top (the project wins key by key). A
* language the plugin has no texts for gets the English ones.
*/
export function applyAdminI18n(config: Config): Config {
const supportedLanguages = config.i18n?.supportedLanguages ?? { en, pl }
const plugin: Record<string, { ipal: Record<string, string> }> = {}
for (const lang of Object.keys(supportedLanguages)) {
plugin[lang] = { ipal: lang === 'pl' ? adminTexts.pl : adminTexts.en }
}
return {
...config,
i18n: {
...config.i18n,
supportedLanguages,
translations: deepMergeSimple(plugin, (config.i18n?.translations ?? {}) as Record<string, unknown>),
},
}
}
+14
View File
@@ -0,0 +1,14 @@
/** A visible admin string in every language the plugin ships. Payload accepts it as `label`, `description`, option `label`, tab `label`, `admin.group`. */
export type AdminText = { en: string; pl: string }
/** Languages the plugin ships admin texts in. */
export const ADMIN_LANGUAGES = ['en', 'pl'] as const
export type AdminLanguage = (typeof ADMIN_LANGUAGES)[number]
/**
* Declares one group of component texts. The Polish set must have exactly the
* English keys, so a missing translation is a type error.
*/
export function defineTexts<T extends Record<string, string>>(texts: { en: T; pl: Record<keyof T, string> }) {
return texts
}
+6
View File
@@ -0,0 +1,6 @@
// Client-safe: types, texts and helpers. The config transform (applyAdminI18n) lives in apply.ts.
export type { AdminLanguage, AdminText } from './define.js'
export { ADMIN_LANGUAGES, defineTexts } from './define.js'
export { formatDateTime, formatNumber, ipalT } from './t.js'
export { adminTexts } from './texts/index.js'
export type { AdminTextKey } from './texts/index.js'
+19
View File
@@ -0,0 +1,19 @@
import type { AdminTextKey } from './texts/index.js'
type TFunction = (key: never, vars?: Record<string, unknown>) => string
/**
* Reads one plugin text through Payload's `t` (from `useTranslation()` in client
* components, `i18n.t` in server components), so a project's own
* `i18n.translations.<lang>.ipal.<key>` wins over the plugin's.
*/
export function ipalT(t: TFunction, key: AdminTextKey, vars?: Record<string, unknown>): string {
return t(`ipal:${key}` as never, vars)
}
/** Number in the admin language's format (1 234 in Polish, 1,234 in English). */
export const formatNumber = (n: number, language: string) => new Intl.NumberFormat(language).format(n)
/** Date and time in the admin language's format. */
export const formatDateTime = (iso: string, language: string, timeZone?: string) =>
new Intl.DateTimeFormat(language, { dateStyle: 'medium', timeStyle: 'short', ...(timeZone ? { timeZone } : {}) }).format(new Date(iso))
+7
View File
@@ -0,0 +1,7 @@
import { defineTexts } from '../define.js'
/** Admin component texts — consent. Placeholders use Payload's {{name}} syntax. */
export const consentTexts = defineTexts({
en: {},
pl: {},
})
+112
View File
@@ -0,0 +1,112 @@
import { defineTexts } from '../define.js'
/**
* Admin component texts — content (statistics, SEO hints, row labels).
* Placeholders use Payload's {{name}} syntax. Plural sets end in One / Few /
* Many / Other (Intl.PluralRules categories); English uses One and Other.
*/
export const contentTexts = defineTexts({
en: {
// Statistics: nav link, view, widget, chart
statsBack: 'Back to statistics',
statsChartDay: '{{day}} · Visits: {{visits}} · Page views: {{views}}',
statsChartTable: 'Table',
statsColDay: 'Day',
statsColDevice: 'Device',
statsColEntryPage: 'Entry page',
statsColLastVisit: 'Last visit',
statsColPage: 'Page',
statsColReferrer: 'Referrer',
statsColViews: 'Views',
statsColVisitor: 'Visitor',
statsConsentedVisits: 'Visits with analytics consent',
statsDeviceDesktop: 'Desktop',
statsDeviceMobile: 'Mobile',
statsDeviceTablet: 'Tablet',
statsDirect: '(direct)',
statsFrom: 'from {{referrer}}',
statsIntro: 'Last 30 days, counted without cookies and without storing IP addresses.',
statsNavLink: 'Overview',
statsNoAccess: 'You do not have access to statistics.',
statsNoData: 'No data yet. It appears after the first visits.',
statsNoVisitors: 'No visitor has accepted analytics cookies yet.',
statsPagesFew: '{{count}} pages',
statsPagesMany: '{{count}} pages',
statsPagesOne: '{{count}} page',
statsPagesOther: '{{count}} pages',
statsPagesPerVisit: 'Pages per visit',
statsPageViews: 'Page views',
statsSinglePageVisits: 'Single-page visits',
statsTitle: 'Statistics',
statsUnknownDevice: 'Unknown device',
statsVisitorErase: 'To erase this visitor’s data, filter the visits list by this visitor ID and delete the results.',
statsVisitorHeading: 'Visitor',
statsVisitorHistory: 'Visitor history (with consent)',
statsVisitorLink: 'Visitor {{id}}',
statsVisitorVisitsFew: '{{count}} visits recorded with analytics consent.',
statsVisitorVisitsMany: '{{count}} visits recorded with analytics consent.',
statsVisitorVisitsOne: '{{count}} visit recorded with analytics consent.',
statsVisitorVisitsOther: '{{count}} visits recorded with analytics consent.',
statsVisits: 'Visits',
statsVisitsPerDay: 'Visits per day',
statsWidgetLink: 'All statistics',
statsWidgetSummary: 'Last 30 days · Visits: {{visits}} · Page views: {{views}}',
// SEO: description check under the search result description
seoDescEmpty: 'Empty. The page uses the site description, the same as every other page.',
seoDescEmptyAutoFill: 'Empty. On save it is filled from the page content; writing your own is better.',
seoDescSameAs: 'Same description as “{{name}}”. Google ignores a description repeated across pages; make each one unique.',
seoDescSameAsSite: 'Same as the site description. Google ignores a description repeated across pages; write one for this page.',
// Array rows without a name
rowLabelItem: 'Item',
},
pl: {
rowLabelItem: 'Element',
seoDescEmpty: 'Puste. Strona użyje opisu witryny, takiego samego jak na innych stronach.',
seoDescEmptyAutoFill: 'Puste. Przy zapisie zostanie uzupełnione treścią strony; lepiej napisać własny opis.',
seoDescSameAs: 'Taki sam opis jak na stronie „{{name}}”. Google pomija opis powtarzany na wielu stronach; każdy powinien być inny.',
seoDescSameAsSite: 'Taki sam jak opis witryny. Google pomija opis powtarzany na wielu stronach; napisz opis tej strony.',
statsBack: 'Wróć do statystyk',
statsChartDay: '{{day}} · Wizyty: {{visits}} · Odsłony: {{views}}',
statsChartTable: 'Tabela',
statsColDay: 'Dzień',
statsColDevice: 'Urządzenie',
statsColEntryPage: 'Strona wejścia',
statsColLastVisit: 'Ostatnia wizyta',
statsColPage: 'Strona',
statsColReferrer: 'Strona odsyłająca',
statsColViews: 'Odsłony',
statsColVisitor: 'Odwiedzający',
statsConsentedVisits: 'Wizyty ze zgodą na analitykę',
statsDeviceDesktop: 'Komputer',
statsDeviceMobile: 'Telefon',
statsDeviceTablet: 'Tablet',
statsDirect: '(bezpośrednio)',
statsFrom: 'z {{referrer}}',
statsIntro: 'Ostatnie 30 dni, liczone bez cookies i bez zapisywania adresów IP.',
statsNavLink: 'Przegląd',
statsNoAccess: 'Brak dostępu do statystyk.',
statsNoData: 'Brak danych. Pojawią się po pierwszych wizytach.',
statsNoVisitors: 'Żaden odwiedzający nie zaakceptował jeszcze cookies analitycznych.',
statsPagesFew: '{{count}} strony',
statsPagesMany: '{{count}} stron',
statsPagesOne: '{{count}} strona',
statsPagesOther: '{{count}} strony',
statsPagesPerVisit: 'Strony na wizytę',
statsPageViews: 'Odsłony',
statsSinglePageVisits: 'Wizyty jednostronicowe',
statsTitle: 'Statystyki',
statsUnknownDevice: 'Nieznane urządzenie',
statsVisitorErase: 'Aby usunąć dane tego odwiedzającego, przefiltruj listę wizyt po jego identyfikatorze i usuń wyniki.',
statsVisitorHeading: 'Odwiedzający',
statsVisitorHistory: 'Historia odwiedzających (za zgodą)',
statsVisitorLink: 'Odwiedzający {{id}}',
statsVisitorVisitsFew: '{{count}} wizyty zapisane za zgodą na analitykę.',
statsVisitorVisitsMany: '{{count}} wizyt zapisanych za zgodą na analitykę.',
statsVisitorVisitsOne: '{{count}} wizyta zapisana za zgodą na analitykę.',
statsVisitorVisitsOther: '{{count}} wizyty zapisanej za zgodą na analitykę.',
statsVisits: 'Wizyty',
statsVisitsPerDay: 'Wizyty dziennie',
statsWidgetLink: 'Wszystkie statystyki',
statsWidgetSummary: 'Ostatnie 30 dni · Wizyty: {{visits}} · Odsłony: {{views}}',
},
})
+12
View File
@@ -0,0 +1,12 @@
import { consentTexts } from './consent.js'
import { contentTexts } from './content.js'
import { integrationsTexts } from './integrations.js'
import { settingsTexts } from './settings.js'
/** Every admin component text, by language. Payload reads them as `ipal:<key>`. */
export const adminTexts = {
en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en },
pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl },
}
export type AdminTextKey = keyof typeof adminTexts.en
@@ -0,0 +1,104 @@
import { defineTexts } from '../define.js'
/** Admin component texts — integrations. Placeholders use Payload's {{name}} syntax. */
export const integrationsTexts = defineTexts({
en: {
// Dashboard alert (IntegrationAlerts)
alertsHeading: 'An integration needs attention. The site still works.',
alertsLink: 'Go to Site integrations',
alertsUnknownError: 'Unknown error.',
// Masked secret field
maskedHide: 'Hide',
maskedShow: 'Show',
// Status banner on an integration's tab (IntegrationStatusBanner)
statusCode: 'Code: {{code}}.',
statusEmailFailing: 'E-mail sending is not working. Form notifications may not arrive.',
statusEmailHint: 'Correct the settings below, save and send a test e-mail.',
statusFailing: '{{label}} is not working.',
statusHint: 'Correct the settings below and save.',
statusLastChecked: 'Last checked {{date}}.',
statusSince: 'Since {{date}}.',
statusTurnstileFailing: 'Spam protection is not working. Forms are accepted without this check.',
statusTurnstileHint: 'Correct the keys below and save. The status updates after the next form submission.',
statusWorking: '{{label}}: working.',
statusWorkingSince: '{{label}}: working since {{date}}.',
// Status messages, by status code
statusEmailGraphUnavailable:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
statusTurnstileInternalError: 'Cloudflare reported an internal error. It usually passes on its own.',
statusTurnstileInvalidSecret: 'Cloudflare rejected the secret key. Both keys must come from the same widget.',
statusTurnstileMissingSecret: 'The secret key is missing.',
statusTurnstileNetworkError: 'The server could not reach Cloudflare.',
statusTurnstileNoSecretKey: 'The secret key is missing, so spam protection is off. Fill in both keys or clear both.',
statusTurnstileNoSiteKey: 'The site key is missing, so spam protection is off. Fill in both keys or clear both.',
// Test e-mail (button + endpoint)
testEmailBody: 'This is a test message from {{site}}. If it arrived, e-mail sending works.',
testEmailBodyGeneric: 'This is a test message from your website. If it arrived, e-mail sending works.',
testEmailFailed: 'The test e-mail was not sent. Check the settings above and try again.',
testEmailForbidden: 'Only an administrator can send a test e-mail.',
testEmailHint: 'Save your changes first. The test uses the saved settings.',
testEmailInvalidRecipient: 'Enter a valid e-mail address, e.g. [email protected].',
testEmailLabel: 'Test e-mail',
testEmailLoggedOut: 'Your session has ended. Log in again.',
testEmailNoConnection: 'Could not reach the server. Check your connection and try again.',
testEmailNotConfigured: 'Fill in the server, user name and password, then save.',
testEmailRecipient: 'Recipient address',
testEmailSend: 'Send test e-mail',
testEmailSending: 'Sending…',
testEmailSent: 'Test e-mail sent to {{to}}.',
testEmailSubject: 'Test e-mail from {{site}}',
testEmailSubjectGeneric: 'Test e-mail from your website',
},
pl: {
alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.',
alertsLink: 'Przejdź do integracji',
alertsUnknownError: 'Nieznany błąd.',
maskedHide: 'Ukryj',
maskedShow: 'Pokaż',
statusCode: 'Kod: {{code}}.',
statusEmailFailing: 'Wysyłka e-mail nie działa. Powiadomienia z formularzy mogą nie docierać.',
statusEmailHint: 'Popraw ustawienia poniżej, zapisz i wyślij testowy e-mail.',
statusFailing: '{{label}}: nie działa.',
statusHint: 'Popraw ustawienia poniżej i zapisz.',
statusLastChecked: 'Ostatnie sprawdzenie: {{date}}.',
statusSince: 'Od {{date}}.',
statusTurnstileFailing: 'Ochrona przed spamem nie działa. Formularze są przyjmowane bez tej kontroli.',
statusTurnstileHint: 'Popraw klucze poniżej i zapisz. Status odświeży się po następnym zgłoszeniu z formularza.',
statusWorking: '{{label}}: działa.',
statusWorkingSince: '{{label}}: działa od {{date}}.',
statusEmailGraphUnavailable:
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
statusTurnstileInternalError: 'Cloudflare zgłosił błąd wewnętrzny. Zwykle ustępuje samoczynnie.',
statusTurnstileInvalidSecret: 'Cloudflare odrzucił klucz tajny. Oba klucze muszą pochodzić z tego samego widżetu.',
statusTurnstileMissingSecret: 'Brak klucza tajnego.',
statusTurnstileNetworkError: 'Serwer nie może połączyć się z Cloudflare.',
statusTurnstileNoSecretKey: 'Brak klucza tajnego, więc ochrona przed spamem jest wyłączona. Uzupełnij oba klucze albo usuń oba.',
statusTurnstileNoSiteKey: 'Brak klucza witryny, więc ochrona przed spamem jest wyłączona. Uzupełnij oba klucze albo usuń oba.',
testEmailBody: 'To jest wiadomość testowa z witryny {{site}}. Jeśli dotarła, wysyłka e-mail działa.',
testEmailBodyGeneric: 'To jest wiadomość testowa z witryny. Jeśli dotarła, wysyłka e-mail działa.',
testEmailFailed: 'Nie wysłano testowego e-maila. Sprawdź ustawienia powyżej i spróbuj ponownie.',
testEmailForbidden: 'Tylko administrator może wysłać testowy e-mail.',
testEmailHint: 'Najpierw zapisz zmiany. Test używa zapisanych ustawień.',
testEmailInvalidRecipient: 'Wpisz poprawny adres e-mail, np. [email protected].',
testEmailLabel: 'Testowy e-mail',
testEmailLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
testEmailNoConnection: 'Brak połączenia z serwerem. Sprawdź połączenie i spróbuj ponownie.',
testEmailNotConfigured: 'Uzupełnij serwer, nazwę użytkownika i hasło, a następnie zapisz.',
testEmailRecipient: 'Adres odbiorcy',
testEmailSend: 'Wyślij testowy e-mail',
testEmailSending: 'Wysyłanie…',
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
},
})
+11
View File
@@ -0,0 +1,11 @@
import { defineTexts } from '../define.js'
/** Admin component texts — settings. Placeholders use Payload's {{name}} syntax. */
export const settingsTexts = defineTexts({
en: {
brandingCredit: 'Technology supported by Intecion.com',
},
pl: {
brandingCredit: 'Technologię wspiera Intecion.com',
},
})
+19 -5
View File
@@ -1,9 +1,16 @@
'use client'
import { useRowLabel } from '@payloadcms/ui'
import { useRowLabel, useTranslation } from '@payloadcms/ui'
import type { AdminText } from '../admin-i18n/define.js'
import { ipalT } from '../admin-i18n/t.js'
export type RowLabelProps = {
/** Shown with the row number when every path is empty, e.g. "Button" → "Button 02". */
fallback?: string
/**
* Shown with the row number when every path is empty, e.g. "Button" → "Button 02".
* A string or `{ en, pl }`; default "Item" in the admin language.
*/
fallback?: AdminText | Record<string, string> | string
/** Dot paths inside the row, tried in order — the first non-empty text wins. */
fields?: string[]
}
@@ -29,11 +36,18 @@ const toText = (v: unknown): string => {
* "Fast delivery") instead of "Item 01", so an editor finds the right row
* without expanding every one. Wire it with `rowLabel()`.
*/
export function RowLabel({ fallback = 'Item', fields = ['heading', 'title', 'label', 'link.label', 'name'] }: RowLabelProps) {
export function RowLabel({ fallback, fields = ['heading', 'title', 'label', 'link.label', 'name'] }: RowLabelProps) {
const { data, rowNumber } = useRowLabel<Record<string, unknown>>()
const { i18n, t } = useTranslation()
for (const f of fields) {
const text = toText(at(data, f))
if (text) {return <span>{text.length > 60 ? `${text.slice(0, 57)}…` : text}</span>}
}
return <span>{`${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}</span>
const name =
typeof fallback === 'string'
? fallback
: fallback
? ((fallback as Record<string, string>)[i18n.language] ?? fallback.en ?? Object.values(fallback)[0])
: ipalT(t, 'rowLabelItem')
return <span>{`${name} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}</span>
}
+3 -2
View File
@@ -7,9 +7,10 @@ import type { RowLabelProps } from './RowLabelComponent.js'
* admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }
*
* Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02".
* `fallback` may be `{ en, pl }`; without it the row reads "Item 01" in the admin language.
* After adding it to a project: `pnpm payload generate:importmap`.
*/
export function rowLabel(fields: string | string[], fallback = 'Item') {
const clientProps: RowLabelProps = { fallback, fields: Array.isArray(fields) ? fields : [fields] }
export function rowLabel(fields: string | string[], fallback?: RowLabelProps['fallback']) {
const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], ...(fallback ? { fallback } : {}) }
return { RowLabel: { clientProps, path: '@intecion/ipal-kit/admin#RowLabel' } }
}
+7 -3
View File
@@ -21,8 +21,12 @@ export function validAnalyticsId(field: AnalyticsIdField, value: unknown): null
return v && ANALYTICS_ID_FORMATS[field].test(v) ? v : null
}
/** Payload field `validate` for an ID field. */
/** Payload field `validate` for an ID field. The message follows the editor's admin language. */
export const validateAnalyticsId =
(field: AnalyticsIdField, example: string) =>
(value: null | string | undefined): string | true =>
!value?.trim() || validAnalyticsId(field, value) !== null || `Unexpected format — expected something like ${example}`
(value: null | string | undefined, options?: { req?: { i18n?: { language?: string } } }): string | true => {
if (!value?.trim() || validAnalyticsId(field, value) !== null) {return true}
return options?.req?.i18n?.language === 'pl'
? `Sprawdź identyfikator. Powinien wyglądać tak: ${example}.`
: `Check the ID. It should look like this: ${example}.`
}
+34 -11
View File
@@ -1,5 +1,7 @@
import type { Field, GroupField } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
/**
* The two field groups every section block shares — same panel, same data
* shape in every project, so the shared <Section>/<SectionHeader> components
@@ -24,12 +26,13 @@ export function buildSectionHeaderField({ name = 'header', fields = [], interfac
name,
type: 'group',
fields: [
{ name: 'eyebrow', type: 'text', admin: { description: 'Small line above the heading. Optional.' }, localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, localized: true },
{ name: 'eyebrow', type: 'text', label: { en: 'Line above heading', pl: 'Tekst nad nagłówkiem' }, localized: true },
{ name: 'heading', type: 'text', label: { en: 'Heading', pl: 'Nagłówek' }, localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, label: { en: 'Introduction', pl: 'Wstęp' }, localized: true },
...fields,
],
interfaceName,
label: { en: 'Section header', pl: 'Nagłówek sekcji' },
}
}
@@ -38,9 +41,9 @@ export type SectionSettingsFieldOptions = {
anchor?: boolean
/**
* Background choices — values map to the project's own classes in <Section>.
* Default Default / Muted / Inverted (dark). `false` → no background select.
* Default Default / Muted / Dark (value `inverted`). `false` → no background select.
*/
backgrounds?: { label: string; value: string }[] | false
backgrounds?: { label: AdminText | string; value: string }[] | false
/** Extra settings (e.g. spacing, width). */
fields?: Field[]
/** Generated TS type name. Default 'SectionSettings'. */
@@ -50,9 +53,9 @@ export type SectionSettingsFieldOptions = {
}
const DEFAULT_BACKGROUNDS = [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
{ label: { en: 'Default', pl: 'Domyślne' }, value: 'default' },
{ label: { en: 'Muted', pl: 'Stonowane' }, value: 'muted' },
{ label: { en: 'Dark', pl: 'Ciemne' }, value: 'inverted' },
]
/** Sidebar group: anchor + background (+ your own) — instead of bgColor / sectionId per block. */
@@ -69,14 +72,34 @@ export function buildSectionSettingsField({
admin: { position: 'sidebar' },
fields: [
...(anchor
? [{ name: 'anchor', type: 'text', admin: { description: 'Section id for #links and section nav, e.g. "pricing".' } } as Field]
? [
{
name: 'anchor',
type: 'text',
admin: {
description: {
en: 'Lets links jump to this section, e.g. pricing for #pricing.',
pl: 'Pozwala linkom przejść do tej sekcji, np. cennik dla #cennik.',
},
},
label: { en: 'Anchor', pl: 'Kotwica' },
} as Field,
]
: []),
...(backgrounds && backgrounds.length
? [{ name: 'background', type: 'select', defaultValue: backgrounds[0].value, options: backgrounds } as Field]
? [
{
name: 'background',
type: 'select',
defaultValue: backgrounds[0].value,
label: { en: 'Background', pl: 'Tło' },
options: backgrounds,
} as Field,
]
: []),
...fields,
],
interfaceName,
label: 'Section settings',
label: { en: 'Section settings', pl: 'Ustawienia sekcji' },
}
}
+9 -6
View File
@@ -1,5 +1,8 @@
import type { Payload } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
@@ -118,6 +121,8 @@ export async function AdminIcon(props: BrandingProps = {}) {
* data — a sensible default here is fine and A0-safe. The client's own brand
* still owns the logo/name; this is a small line stating who supports the tech.
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
* The default text follows the admin language (`ipal:brandingCredit`, which a
* project can also override in `i18n.translations`).
*
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
* (login screen footer). `variant` adjusts placement:
@@ -125,13 +130,11 @@ export async function AdminIcon(props: BrandingProps = {}) {
* - 'login' → centered line below the login form
*/
export function IntecionCredit(
props: { text?: string; url?: string; variant?: 'login' | 'nav' } = {},
props: { i18n?: { t: (key: never, vars?: Record<string, unknown>) => string }; text?: string; url?: string; variant?: 'login' | 'nav' } = {},
) {
const {
text = 'Technology supported by Intecion.com',
url = 'https://intecion.com',
variant = 'nav',
} = props
const { i18n, url = 'https://intecion.com', variant = 'nav' } = props
// A project's own text wins; otherwise the plugin's text in the admin language.
const text = props.text ?? (i18n ? ipalT(i18n.t, 'brandingCredit') : settingsTexts.en.brandingCredit)
const style =
variant === 'login'
? {
+16 -4
View File
@@ -9,6 +9,12 @@ export type CookieTableLabels = {
purpose: string
}
/** Default column headings, per language. */
export const COOKIE_TABLE_LABELS: { en: CookieTableLabels; pl: CookieTableLabels } = {
en: { name: 'Cookie', category: 'Category', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' },
pl: { name: 'Plik cookie', category: 'Kategoria', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' },
}
type CookieTableProps = {
/** Optional caption above the table. */
caption?: string
@@ -16,8 +22,13 @@ type CookieTableProps = {
categories?: ConsentTexts['categories']
/** Classes per element; nothing is styled by default. */
classNames?: Partial<Record<'caption' | 'table' | 'td' | 'th' | 'tr', string>>
/** Column headings in the page's language — from the project (panel field or page content). */
labels: CookieTableLabels
/**
* Column headings — from the project (panel field or page content). Missing
* ones use the defaults for `locale` (Polish for 'pl', else English).
*/
labels?: Partial<CookieTableLabels>
/** Page language — picks the default column headings. */
locale?: string
/** From getCookieTable({ payload, locale }) — Cookie Settings → Cookies. */
rows: CookieTableRow[]
}
@@ -29,10 +40,11 @@ type CookieTableProps = {
* component (no state).
*
* const rows = await getCookieTable({ payload, locale })
* <CookieTable rows={rows} labels={…from the panel…} categories={texts.categories} />
* <CookieTable rows={rows} locale={locale} categories={texts.categories} /> // labels={…} to change the headings
*/
export function CookieTable({ caption, categories, classNames = {}, labels, rows }: CookieTableProps) {
export function CookieTable({ caption, categories, classNames = {}, labels: given, locale, rows }: CookieTableProps) {
if (rows.length === 0) {return null}
const labels = { ...(locale?.toLowerCase().startsWith('pl') ? COOKIE_TABLE_LABELS.pl : COOKIE_TABLE_LABELS.en), ...Object.fromEntries(Object.entries(given ?? {}).filter(([, v]) => v)) }
return (
<table className={classNames.table}>
{caption ? <caption className={classNames.caption}>{caption}</caption> : null}
+15
View File
@@ -0,0 +1,15 @@
import type { AdminText } from '../admin-i18n/index.js'
import type { ConsentCategory } from './categories.js'
import { CONSENT_CATEGORIES } from './categories.js'
/** Admin labels of the consent categories (select options in the panel). Values stay the category keys. */
export const CONSENT_CATEGORY_LABELS: Record<ConsentCategory, AdminText> = {
analytics: { en: 'Analytics', pl: 'Analityczne' },
functional: { en: 'Functional', pl: 'Funkcjonalne' },
marketing: { en: 'Marketing', pl: 'Marketingowe' },
necessary: { en: 'Necessary', pl: 'Niezbędne' },
}
/** Select options for a consent category field. */
export const consentCategoryOptions = () => CONSENT_CATEGORIES.map((c) => ({ label: CONSENT_CATEGORY_LABELS[c], value: c }))
+14 -6
View File
@@ -6,6 +6,7 @@ import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
/**
* Consent log — proof of consent (GDPR Art. 7(1): the controller must be able
@@ -45,20 +46,27 @@ export function buildConsentLogCollection(): CollectionConfig {
},
admin: {
defaultColumns: ['consentId', 'version', 'createdAt'],
description: 'Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.',
group: 'Settings',
description: {
en: 'Proof of each cookie banner choice, stored with a random ID and no personal data.',
pl: 'Dowód każdego wyboru na banerze cookies, zapisany z losowym identyfikatorem, bez danych osobowych.',
},
group: { en: 'Privacy', pl: 'Prywatność' },
useAsTitle: 'consentId',
},
fields: [
{ name: 'consentId', type: 'text', index: true, required: true },
{ name: 'version', type: 'number', required: true },
{ name: 'consentId', type: 'text', index: true, label: { en: 'Consent ID', pl: 'Identyfikator zgody' }, required: true },
{ name: 'version', type: 'number', label: { en: 'Consent version', pl: 'Wersja zgody' }, required: true },
{
name: 'choices',
type: 'group',
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const })),
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const, label: CONSENT_CATEGORY_LABELS[c] })),
label: { en: 'Choices', pl: 'Wybór' },
},
],
labels: { plural: 'Consent records', singular: 'Consent record' },
labels: {
plural: { en: 'Consent records', pl: 'Rejestr zgód' },
singular: { en: 'Consent record', pl: 'Zapis zgody' },
},
timestamps: true,
}
}
+40 -9
View File
@@ -8,8 +8,8 @@ import { getSystemPagePath } from '../pages/index.js'
import { getGlobal } from '../payload/index.js'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
/** English fallback used when the global has no value for a field. */
const FALLBACK: ConsentTexts = {
/** English defaults, used per field when the global has no value. */
export const CONSENT_FALLBACK: ConsentTexts = {
buttons: {
acceptAll: 'Accept all',
back: 'Back',
@@ -19,8 +19,8 @@ const FALLBACK: ConsentTexts = {
settings: 'Settings',
},
categories: {
analytics: { description: 'Help us understand usage.', title: 'Analytics' },
functional: { description: 'Remember preferences.', title: 'Functional' },
analytics: { description: 'Help us understand how the site is used.', title: 'Analytics' },
functional: { description: 'Remember your preferences.', title: 'Functional' },
marketing: { description: 'Used to show relevant ads.', title: 'Marketing' },
necessary: {
description:
@@ -35,8 +35,38 @@ const FALLBACK: ConsentTexts = {
settingsTitle: 'Cookie settings',
}
/** Polish defaults — used on a page whose locale is Polish. */
export const CONSENT_FALLBACK_PL: ConsentTexts = {
buttons: {
acceptAll: 'Akceptuj wszystkie',
back: 'Wstecz',
close: 'Zamknij',
reject: 'Odrzuć',
save: 'Zapisz ustawienia',
settings: 'Ustawienia',
},
categories: {
analytics: { description: 'Pomagają zrozumieć, jak odwiedzający korzystają z witryny.', title: 'Analityczne' },
functional: { description: 'Zapamiętują wybrane ustawienia.', title: 'Funkcjonalne' },
marketing: { description: 'Służą do wyświetlania dopasowanych reklam.', title: 'Marketingowe' },
necessary: {
description: 'Niezbędne do działania witryny, w tym do zapamiętania języka i motywu. Zawsze włączone.',
title: 'Niezbędne',
},
},
details: { cookies: 'Używane cookies', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' },
message:
'Używamy plików cookies, aby witryna działała, aby analizować ruch i ulepszać witrynę. Można zaakceptować wszystkie, odrzucić te, które nie są niezbędne, lub wybrać je samodzielnie.',
privacyLink: null,
settingsTitle: 'Ustawienia cookies',
}
/** Defaults for a page language: Polish for 'pl' / 'pl-PL', English for anything else. */
export const consentFallback = (locale?: string): ConsentTexts =>
locale?.toLowerCase().startsWith('pl') ? CONSENT_FALLBACK_PL : CONSENT_FALLBACK
/** Last-resort link text — only when neither the panel nor the page has one. */
const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
const privacyFallbackLabel = (locale?: string) => (locale?.toLowerCase().startsWith('pl') ? 'Polityka prywatności' : 'Privacy policy')
type CookieSettingsData = {
alwaysActiveLabel?: null | string
@@ -104,8 +134,8 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom
}
/**
* Resolves consent banner texts from the CookieSettings global, falling back to
* English defaults per field. The privacy-policy link target comes from the
* Resolves consent banner texts from the CookieSettings global, falling back per
* field to the defaults in the page's language (Polish for 'pl', else English). The privacy-policy link target comes from the
* pages module (system page role, read automatically); its text from
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
*/
@@ -117,6 +147,7 @@ export async function getConsentTexts({
settingsSlug = 'site-settings',
}: GetConsentTextsArgs): Promise<ConsentTexts> {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
const FALLBACK = consentFallback(locale)
const categories = {} as ConsentTexts['categories']
for (const cat of CONSENT_CATEGORIES) {
@@ -140,7 +171,7 @@ export async function getConsentTexts({
g.privacyLinkLabel?.trim() ||
privacyPolicy?.label?.trim() ||
resolveLocalized(page.title, locale).trim() ||
FALLBACK_PRIVACY_LABEL
privacyFallbackLabel(locale)
privacyLink = { href, label }
}
}
@@ -165,7 +196,7 @@ export async function getConsentTexts({
message: g.message || FALLBACK.message,
privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
// optional copy — no English fallback: empty in the panel = element not rendered
// optional copy — no fallback: empty in the panel = element not rendered
...(g.eyebrow?.trim() ? { eyebrow: g.eyebrow.trim() } : {}),
...(g.title?.trim() ? { title: g.title.trim() } : {}),
...(g.settingsDescription?.trim() ? { settingsDescription: g.settingsDescription.trim() } : {}),
+2 -1
View File
@@ -8,9 +8,10 @@ export {
REJECT_ALL_CONSENT,
} from './categories.js'
export type { ConsentCategory, ConsentState } from './categories.js'
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { getConsentTexts, getCookieTable } from './getConsentTexts.js'
export { CONSENT_FALLBACK, CONSENT_FALLBACK_PL, consentFallback, getConsentTexts, getCookieTable } from './getConsentTexts.js'
export type { CookieTableRow } from './getConsentTexts.js'
export { setDefaultConsent, updateConsent } from './googleConsent.js'
export {
@@ -7,6 +7,7 @@ import { useEffect, useState } from 'react'
import type { CookieScanLabels } from './labels.js'
import type { CookieScanSummary } from './types.js'
import { formatDateTime } from '../../admin-i18n/t.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
type CrawlState = {
@@ -48,7 +49,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
const [crawlStarting, setCrawlStarting] = useState(false)
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
const when = (iso: null | string) => (iso ? new Date(iso).toLocaleString(i18n.language) : '')
const when = (iso: null | string) => (iso ? formatDateTime(iso, i18n.language) : '')
useEffect(() => {
if (!crawl) {return}
@@ -155,7 +156,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
{t.crawlButton}
</Button>
<span role="status">
{crawlState && !crawlState.configured ? `${t.crawlNotConfigured} (${crawlState.missing.join(', ')})` : null}
{crawlState && !crawlState.configured ? t.crawlNotConfigured : null}
{crawlState?.configured && crawlState.status === 'running' ? fill(t.crawlRunning, { startedAt: when(crawlState.startedAt) }) : null}
{crawlState?.configured && crawlState.status === 'done'
? fill(t.crawlDone, { finishedAt: when(crawlState.finishedAt), newUnknown: crawlState.summary?.newUnknown ?? 0, pages: crawlState.summary?.pages ?? 0, violations: crawlState.summary?.violations ?? 0 })
+1 -1
View File
@@ -95,7 +95,7 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: 'Settings',
group: { en: 'Privacy', pl: 'Prywatność' },
listSearchableFields: ['name', 'vendor'],
useAsTitle: 'name',
},
@@ -122,7 +122,7 @@ export function buildCookieCrawlEndpoints({
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`)
await write(req, { error: `Could not reach the scanner service: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
await write(req, { error: 'The checking service could not be reached. Please try again later.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 })
}
return Response.json({ ok: true, status: 'running' }, { status: 202 })
@@ -155,7 +155,7 @@ export function buildCookieCrawlEndpoints({
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`)
await write(req, { error: `Saving the result failed: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
await write(req, { error: 'The result could not be saved. Please run the check again.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ ok: false }, { status: 500 })
}
},
+7 -7
View File
@@ -3,7 +3,7 @@ import type { GlobalConfig } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { labelRecord } from '../labels.js'
import { labelFor, labelRecord } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
/**
@@ -20,16 +20,16 @@ export function buildCookieCrawlGlobal(labels: Record<string, CookieScanLabels>)
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: { description: L('crawlGlobalDescription'), group: 'Settings' },
admin: { description: L('crawlGlobalDescription'), group: { en: 'Privacy', pl: 'Prywatność' } },
fields: [
{
name: 'notifyEmails',
type: 'text',
admin: { description: L('notifyEmailsDescription') },
label: L('notifyEmails'),
validate: (value: null | string | undefined) => {
validate: (value: null | string | undefined, { req }: { req: { i18n?: { language?: string } } }) => {
const list = (value ?? '').split(',').map((v) => v.trim()).filter(Boolean)
return list.every((v) => /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(v)) || 'Comma-separated e-mail addresses.'
return list.every((v) => /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(v)) || labelFor(labels, req?.i18n?.language, 'notifyEmailsInvalid')
},
},
{
@@ -56,9 +56,9 @@ export function buildCookieCrawlGlobal(labels: Record<string, CookieScanLabels>)
fields: [
{ name: 'pages', type: 'number', admin: ro, label: L('crawlPages') },
{ name: 'violations', type: 'number', admin: ro, label: L('crawlViolations') },
{ name: 'newUnknown', type: 'number', admin: ro, label: L('unknown') },
{ name: 'created', type: 'number', admin: ro },
{ name: 'updated', type: 'number', admin: ro },
{ name: 'newUnknown', type: 'number', admin: ro, label: L('crawlNewUnknown') },
{ name: 'created', type: 'number', admin: ro, label: L('crawlCreated') },
{ name: 'updated', type: 'number', admin: ro, label: L('crawlUpdated') },
],
label: false,
},
+1 -1
View File
@@ -132,7 +132,7 @@ export async function finishCrawl({
...common,
data: {
// Not a failure, but the "after accept" half saw no consent — say so where the editor looks.
error: result.accepted ? null : 'The "Accept all" button was not found (acceptSelector), so the second run had no consent.',
error: result.accepted ? null : 'The "Accept all" button was not found, so the site could not be checked after consent.',
finishedAt: now,
jobId: null,
pages: result.pages,
+87 -77
View File
@@ -1,5 +1,5 @@
/**
* Admin labels of the cookie scanner, per admin language. Payload picks the
* Admin labels of the cookie scanner (review list, scan box, site check), per admin language. Payload picks the
* user's admin language from a `{ en, pl }` record; a language missing here falls
* back to English. Projects add or change languages with `cookieScanner.labels`.
*/
@@ -16,6 +16,7 @@ export type CookieScanLabels = {
collectionDescription: string
cookie: string
crawlButton: string
crawlCreated: string
crawlDone: string
crawlError: string
crawlFailed: string
@@ -23,6 +24,7 @@ export type CookieScanLabels = {
crawlGlobalDescription: string
crawlIdle: string
crawlIntro: string
crawlNewUnknown: string
crawlNotConfigured: string
crawlPages: string
crawlRequests: string
@@ -31,6 +33,7 @@ export type CookieScanLabels = {
crawlStateFailed: string
crawlStateRunning: string
crawlStatus: string
crawlUpdated: string
crawlViolations: string
database: string
domain: string
@@ -54,6 +57,7 @@ export type CookieScanLabels = {
necessary: string
notifyEmails: string
notifyEmailsDescription: string
notifyEmailsInvalid: string
plural: string
project: string
purpose: string
@@ -88,161 +92,167 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
en: {
name: 'Name',
accepted: 'Accepted',
alertBody: 'Non-necessary cookies or trackers load before consent, or the site sets cookies nobody has described yet. Check the review list.',
alertFailed: 'Cookie crawl failed: {error}',
alertLink: 'Open Cookie review →',
alertTitle: 'Cookie crawl: {violations} violations, {newUnknown} new unknown cookies.',
alertBody: 'Cookies that are not necessary load before consent, or some cookies have no description yet. Check the cookie review.',
alertFailed: 'The cookie check failed: {error}',
alertLink: 'Open cookie review',
alertTitle: 'Cookie check: violations: {violations}, new unknown cookies: {newUnknown}.',
analytics: 'Analytics',
beforeConsentOn: 'before consent on {pages}',
category: 'Category',
categoryRequired: 'Pick a category before accepting.',
collectionDescription:
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
categoryRequired: 'Choose a category before accepting.',
collectionDescription: 'Accept a cookie to add it to the cookie list; a new scan never overwrites your edits.',
cookie: 'Cookie',
crawlButton: 'Crawl site',
crawlDone: 'Last crawl {finishedAt}: {pages} pages, {violations} violations, {newUnknown} new unknown.',
crawlButton: 'Check site',
crawlCreated: 'New drafts',
crawlDone: 'Last check {finishedAt}: pages: {pages}, violations: {violations}, new unknown: {newUnknown}.',
crawlError: 'Error',
crawlFailed: 'The last crawl failed: {error}',
crawlGlobal: 'Cookie crawl',
crawlGlobalDescription: 'The latest browser crawl only. Start one from Cookie review → Crawl site.',
crawlIdle: 'Never run',
crawlIntro: 'Opens the site in a browser twice — without consent and after "Accept all" — and records cookies, storage and third-party requests. New findings become drafts.',
crawlNotConfigured: 'The crawl needs IPAL_COOKIE_SCAN_URL and IPAL_COOKIE_SCAN_TOKEN on the server.',
crawlPages: 'Pages crawled',
crawlFailed: 'The last check failed: {error}',
crawlGlobal: 'Cookie check',
crawlGlobalDescription: 'Result of the latest site check, started in Cookie review.',
crawlIdle: 'Not run yet',
crawlIntro: 'Opens the site in a browser before and after "Accept all", and records cookies, storage and requests to other services.',
crawlNewUnknown: 'New unknown cookies',
crawlNotConfigured: 'The site check is not set up on the server. Ask your administrator.',
crawlPages: 'Pages checked',
crawlRequests: 'Third-party requests',
crawlRunning: 'Crawling… started {startedAt}.',
crawlRunning: 'Checking… started {startedAt}.',
crawlStateDone: 'Done',
crawlStateFailed: 'Failed',
crawlStateRunning: 'Running',
crawlStatus: 'Status',
crawlUpdated: 'Updated drafts',
crawlViolations: 'Violations',
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
emailIntro: 'The latest cookie crawl of {site} found:',
emailSubject: 'Cookie crawl of {site}: {violations} violations, {newUnknown} new unknown',
emailIntro: 'The latest cookie check of {site} found:',
emailSubject: 'Cookie check of {site}: violations: {violations}, new unknown cookies: {newUnknown}',
finishedAt: 'Finished',
functional: 'Functional',
integration: 'Plugin integration',
integration: 'Built-in integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration with cookies is switched on.',
lastScannedAt: 'Last seen by a scan',
listed: 'In the cookie list',
listedDescription: 'Already in Cookie Settings → Cookies.',
integrationsNone: 'No integration that uses cookies is on.',
lastScannedAt: 'Last found',
listed: 'In cookie list',
listedDescription: 'Already in the cookie list of the cookie banner.',
localStorage: 'Local storage',
manual: 'Added by hand',
marketing: 'Marketing',
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
namesHint: 'Optional. Other cookie names, one per line. They are looked up in the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
notifyEmails: 'E-mail warnings to',
notifyEmailsDescription: 'Comma-separated addresses. After a crawl with violations or new unknown cookies, a warning is sent through the site\'s mail setup. Empty = no e-mail.',
notifyEmails: 'Warning e-mails to',
notifyEmailsDescription: 'Comma-separated addresses that get a warning when a check finds problems; leave empty for none.',
notifyEmailsInvalid: 'Enter e-mail addresses separated by commas, e.g. [email protected], [email protected].',
plural: 'Cookie review',
project: 'Project declaration',
project: 'Site configuration',
purpose: 'Purpose',
rejected: 'Rejected',
retention: 'Retention',
retention: 'Duration',
scanButton: 'Scan cookies',
scanError: 'The scan failed.',
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
scanError: 'The scan failed. Please try again.',
scanIntro: 'Adds the cookies of the integrations in use as drafts to review.',
scanning: 'Scanning…',
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
scanResult: 'New: {created}, updated: {updated}, unchanged: {unchanged}, unknown: {unknown}.',
seenBeforeConsent: 'Seen before consent',
sessionStorage: 'Session storage',
setBeforeConsent: 'Set before consent',
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
singular: 'Cookie review entry',
setBeforeConsentDescription: 'Set before the visitor decides, which only necessary cookies may be.',
singular: 'Cookie',
source: 'Found by',
sourceDetail: 'Source',
startedAt: 'Started',
startedBy: 'Started by',
status: 'Status',
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
statusDescription: 'Accepted cookies are added to the cookie list; rejecting never removes them from it.',
storage: 'Stored in',
unknown: 'Unknown — fill in',
unknown: 'Unknown',
vendor: 'Provider',
violation: 'Violation',
violationDescription: 'Seen before consent in the latest crawl and not necessary.',
violationDescription: 'Not necessary, yet seen before consent in the latest site check.',
violationDetail: 'Violation details',
},
pl: {
name: 'Nazwa',
accepted: 'Zaakceptowany',
alertBody: 'Cookies lub skrypty śledzące, które nie są niezbędne, ładują się przed zgodą — albo strona ustawia cookies, których nikt jeszcze nie opisał. Sprawdź listę przeglądu.',
alertFailed: 'Skan cookies się nie powiódł: {error}',
alertLink: 'Otwórz Przegląd cookies →',
alertTitle: 'Skan cookies: naruszeń {violations}, nowych nieznanych cookies {newUnknown}.',
alertBody: 'Cookies, które nie są niezbędne, ładują się przed zgodą albo część cookies nie ma jeszcze opisu. Sprawdź przegląd cookies.',
alertFailed: 'Kontrola cookies nie powiodła się: {error}',
alertLink: 'Otwórz przegląd cookies',
alertTitle: 'Kontrola cookies: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}.',
analytics: 'Analityczne',
beforeConsentOn: 'przed zgodą na {pages}',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription:
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
collectionDescription: 'Zaakceptuj plik cookie, aby dodać go do listy cookies; kolejny skan nie nadpisze zmian.',
cookie: 'Cookie',
crawlButton: 'Przeskanuj stronę',
crawlDone: 'Ostatni skan {finishedAt}: stron {pages}, naruszeń {violations}, nowych nieznanych {newUnknown}.',
crawlButton: 'Sprawdź witrynę',
crawlCreated: 'Nowe szkice',
crawlDone: 'Ostatnia kontrola {finishedAt}: strony: {pages}, naruszenia: {violations}, nowe nieznane: {newUnknown}.',
crawlError: 'Błąd',
crawlFailed: 'Ostatni skan się nie powiódł: {error}',
crawlGlobal: 'Skan cookies przeglądarką',
crawlGlobalDescription: 'Tylko ostatni skan przeglądarką. Uruchom go w Przeglądzie cookies → Przeskanuj stronę.',
crawlIdle: 'Nie uruchamiano',
crawlIntro: 'Otwiera stronę w przeglądarce dwa razy — bez zgody i po „Akceptuj wszystkie” — i zapisuje cookies, pamięć przeglądarki i zapytania do zewnętrznych serwisów. Nowe znaleziska trafiają jako szkice.',
crawlNotConfigured: 'Skan przeglądarką wymaga IPAL_COOKIE_SCAN_URL i IPAL_COOKIE_SCAN_TOKEN na serwerze.',
crawlPages: 'Przeskanowane strony',
crawlRequests: 'Zapytania do zewnętrznych serwisów',
crawlRunning: 'Skanowanie… rozpoczęte {startedAt}.',
crawlFailed: 'Ostatnia kontrola nie powiodła się: {error}',
crawlGlobal: 'Kontrola cookies',
crawlGlobalDescription: 'Wynik ostatniej kontroli witryny uruchomionej w przeglądzie cookies.',
crawlIdle: 'Jeszcze nie uruchomiono',
crawlIntro: 'Otwiera witrynę w przeglądarce przed i po „Akceptuj wszystkie” i zapisuje cookies, pamięć przeglądarki oraz zapytania do innych serwisów.',
crawlNewUnknown: 'Nowe nieznane cookies',
crawlNotConfigured: 'Kontrola witryny nie jest skonfigurowana na serwerze. Skontaktuj się z administratorem.',
crawlPages: 'Sprawdzone strony',
crawlRequests: 'Zapytania zewnętrzne',
crawlRunning: 'Sprawdzanie… rozpoczęte {startedAt}.',
crawlStateDone: 'Gotowe',
crawlStateFailed: 'Błąd',
crawlStateRunning: 'W toku',
crawlStatus: 'Status',
crawlUpdated: 'Zaktualizowane szkice',
crawlViolations: 'Naruszenia',
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
emailIntro: 'Ostatni skan cookies strony {site} znalazł:',
emailSubject: 'Skan cookies {site}: naruszeń {violations}, nowych nieznanych {newUnknown}',
finishedAt: 'Zakończony',
emailIntro: 'Ostatnia kontrola cookies witryny {site} wykazała:',
emailSubject: 'Kontrola cookies {site}: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}',
finishedAt: 'Zakończono',
functional: 'Funkcjonalne',
integration: 'Integracja wtyczki',
integration: 'Wbudowana integracja',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja z plikami cookie nie jest włączona.',
lastScannedAt: 'Ostatnio widziany w skanie',
integrationsNone: 'Żadna integracja używająca cookies nie jest włączona.',
lastScannedAt: 'Ostatnio znaleziony',
listed: 'Na liście cookies',
listedDescription: 'Już jest w Ustawieniach cookies → Cookies.',
listedDescription: 'Już jest na liście cookies banera.',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
marketing: 'Marketingowe',
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
namesHint: 'Opcjonalnie. Inne nazwy cookies, po jednej w wierszu. Zostaną wyszukane w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku. Po skanie z naruszeniami lub nowymi nieznanymi cookies wysyłane jest ostrzeżenie przez konfigurację poczty strony. Puste = bez e-maili.',
notifyEmailsDescription: 'Adresy po przecinku, na które trafi ostrzeżenie, gdy kontrola wykryje problemy; zostaw puste, aby nie wysyłać.',
notifyEmailsInvalid: 'Wpisz adresy e-mail oddzielone przecinkami, np. [email protected], [email protected].',
plural: 'Przegląd cookies',
project: 'Deklaracja projektu',
project: 'Konfiguracja witryny',
purpose: 'Cel',
rejected: 'Odrzucony',
retention: 'Czas przechowywania',
retention: 'Okres',
scanButton: 'Skanuj cookies',
scanError: 'Skan się nie powiódł.',
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
scanError: 'Skanowanie nie powiodło się. Spróbuj ponownie.',
scanIntro: 'Dodaje cookies używanych integracji jako szkice do przejrzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
seenBeforeConsent: 'Widoczny przed zgodą',
sessionStorage: 'Session storage',
setBeforeConsent: 'Ustawiany przed zgodą',
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
singular: 'Wpis przeglądu cookies',
setBeforeConsentDescription: 'Ustawiany, zanim odwiedzający zdecyduje, co wolno tylko niezbędnym cookies.',
singular: 'Plik cookie',
source: 'Źródło',
sourceDetail: 'Skąd',
startedAt: 'Rozpoczęty',
startedBy: 'Uruchomił',
sourceDetail: 'Szczegóły źródła',
startedAt: 'Rozpoczęto',
startedBy: 'Uruchomił(a)',
status: 'Status',
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
storage: 'Przechowywany w',
unknown: 'Nieznany — uzupełnij',
statusDescription: 'Zaakceptowane cookies trafiają na listę cookies; odrzucenie nigdy ich z niej nie usuwa.',
storage: 'Miejsce zapisu',
unknown: 'Nieznane',
vendor: 'Dostawca',
violation: 'Naruszenie',
violationDescription: 'Widoczny przed zgodą w ostatnim skanie i nie jest niezbędny.',
violationDescription: 'Nie jest niezbędny, a pojawił się przed zgodą w ostatniej kontroli witryny.',
violationDetail: 'Szczegóły naruszenia',
},
}
@@ -16,7 +16,7 @@ export type ConstructionNoticeClassNames = {
}
/**
* The "site under construction" notice (Site Settings → Under construction).
* The maintenance mode notice (Site settings → Maintenance).
* Opens after a redirect from a blocked address (?notice=construction, then
* removed from the URL) and when a visitor clicks a link to a page that isn't
* available — the click is cancelled. Closes with its button or Escape.
+40 -10
View File
@@ -3,8 +3,8 @@ import type { Field } from 'payload'
const whenEnabled = (_: unknown, siblingData: { enabled?: boolean } | undefined) => Boolean(siblingData?.enabled)
/**
* Site Settings → "Under construction" tab: a developer tool for a site that
* isn't finished. When enabled, only the homepage and the chosen pages are
* Site settings → "Maintenance" tab (maintenance mode) for a site that isn't
* finished. When enabled, only the homepage and the chosen pages are
* reachable — any other address redirects to the homepage with a notice, and a
* link to another page shows the notice instead of navigating. One rule for
* every visitor (pages stay static, there is no per-user check).
@@ -20,23 +20,53 @@ export function buildConstructionFields(pagesSlug: string): Field[] {
name: 'enabled',
type: 'checkbox',
admin: {
description:
'Only the homepage and the pages below can be opened. Other addresses redirect to the homepage with the notice; links to other pages show it instead of navigating.',
description: {
en: 'Visitors can open only the homepage and the pages below; other links show a notice.',
pl: 'Odwiedzający mogą otworzyć tylko stronę główną i strony poniżej; inne linki pokazują komunikat.',
},
},
defaultValue: false,
label: 'Site under construction',
label: { en: 'Maintenance mode', pl: 'Tryb prac technicznych' },
},
{
name: 'allowedPages',
type: 'relationship',
admin: { condition: whenEnabled, description: 'The homepage is always available.' },
admin: {
condition: whenEnabled,
description: { en: 'The homepage is always available.', pl: 'Strona główna jest zawsze dostępna.' },
},
hasMany: true,
label: 'Pages still available',
label: { en: 'Available pages', pl: 'Dostępne strony' },
relationTo: pagesSlug as never,
},
{ name: 'title', type: 'text', admin: { condition: whenEnabled }, label: 'Notice title', localized: true },
{ name: 'message', type: 'textarea', admin: { condition: whenEnabled }, label: 'Notice text', localized: true },
{ name: 'buttonLabel', type: 'text', admin: { condition: whenEnabled }, label: 'Close button label', localized: true },
{
name: 'title',
type: 'text',
admin: { condition: whenEnabled },
label: { en: 'Notice title', pl: 'Tytuł komunikatu' },
localized: true,
},
{
name: 'message',
type: 'textarea',
admin: { condition: whenEnabled },
label: { en: 'Notice text', pl: 'Treść komunikatu' },
localized: true,
},
{
name: 'buttonLabel',
type: 'text',
admin: {
condition: whenEnabled,
description: {
en: 'Leave empty to show a × sign.',
pl: 'Zostaw puste, aby pokazać znak ×.',
},
placeholder: { en: 'Close', pl: 'Zamknij' },
},
label: { en: 'Close button label', pl: 'Etykieta przycisku zamknięcia' },
localized: true,
},
],
label: false,
},
+19 -3
View File
@@ -1,5 +1,6 @@
import type { Field, RelationshipField } from 'payload'
import type { AdminText } from '../admin-i18n/index.js'
import type { ContentOption } from './types.js'
import { archiveFieldName } from './types.js'
@@ -16,17 +17,32 @@ import { archiveFieldName } from './types.js'
*/
export function buildArchiveFields(content: ContentOption, pagesSlug: string): Field[] {
return content.collections.map((collection): RelationshipField => {
const label = collection.label ?? collection.slug
const name = collectionName(collection.label, collection.slug)
return {
name: archiveFieldName(collection.slug),
type: 'relationship',
admin: {
description: `Page listing ${label}. Its slug becomes the URL segment for entries (e.g. /pl/artykuly/moj-wpis).`,
description: {
en: 'Page that lists the entries; its address (URL) starts the address of each entry.',
pl: 'Strona z listą wpisów; jej adres (URL) rozpoczyna adres każdego wpisu.',
},
},
label: `${label} — archive page`,
label: { en: `${name.en} archive`, pl: `Archiwum: ${name.pl}` },
maxDepth: 1,
relationTo: pagesSlug,
}
})
}
/**
* The collection's name in each admin language: the project's `label` (a
* string, or `{ en, pl }`), else the slug made readable (`blog-posts` → "Blog posts").
*/
function collectionName(label: AdminText | string | undefined, slug: string): AdminText {
if (label && typeof label === 'object') {return { en: label.en, pl: label.pl || label.en }}
if (typeof label === 'string' && label.trim()) {return { en: label, pl: label }}
const words = slug.replace(/[-_]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase().trim()
const readable = words.charAt(0).toUpperCase() + words.slice(1)
return { en: readable, pl: readable }
}
+3 -1
View File
@@ -1,3 +1,5 @@
import type { AdminText } from '../admin-i18n/index.js'
/**
* A collection whose entries live under an archive page, e.g. blog posts at
* /pl/artykuly/moj-post.
@@ -10,7 +12,7 @@
*/
export type ContentCollectionOption = {
/** Admin label for the archive assignment. Defaults to the slug. */
label?: string
label?: AdminText | string
/** Entries per page in listings. Defaults to 10. */
perPage?: number
/** Slug of the client's collection, e.g. 'posts'. */
+8 -4
View File
@@ -112,7 +112,11 @@ export const graphAdapter =
payload.logger.error(
'[ipal] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.',
)
return { error: 'Graph is not configured (missing env vars).', sent: false }
return {
code: 'graph-not-configured',
error: 'Microsoft Graph is not set up on the server. Ask your administrator.',
sent: false,
}
}
// Display name on the From, WITHOUT triggering Send-As.
@@ -132,7 +136,7 @@ export const graphAdapter =
const to = toRecipients(message.to)
if (to.length === 0) {
payload.logger.error('[ipal] Email not sent: no valid recipient.')
return { error: 'No valid recipient.', sent: false }
return { error: 'Enter a valid recipient address.', sent: false }
}
// Graph accepts either HTML or Text; Payload gives us html and/or text.
@@ -183,11 +187,11 @@ export const graphAdapter =
}
const detail = await res.text()
payload.logger.error(`[ipal] Graph sendMail failed (${res.status}): ${detail}`)
return { error: `Graph sendMail failed (${res.status}).`, sent: false }
return { detail: `Microsoft Graph refused the e-mail (${res.status}).`, error: 'The e-mail was not sent.', sent: false }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
payload.logger.error(`[ipal] Graph send error: ${msg}`)
return { error: 'Graph send error.', sent: false }
return { detail: msg, error: 'The e-mail was not sent.', sent: false }
}
},
})
+2 -1
View File
@@ -122,7 +122,8 @@ export const mailAdapter =
graphFallback
? {
code: 'graph-unavailable',
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.',
message:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
state: 'degraded',
}
: { state: 'ok' },
+3 -3
View File
@@ -60,9 +60,9 @@ export const panelSmtpAdapter =
if (!host || !user || !pass) {
payload.logger.error(
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
'[ipal] Email not sent: SMTP host, user or password is empty in Site integrations → E-mail sending.',
)
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
return { code: 'not-configured', error: 'Fill in the server, user name and password.', sent: false }
}
// The panel is the source of truth for the sender; fall back to whatever
@@ -102,7 +102,7 @@ export const panelSmtpAdapter =
// shouldn't fail loudly because the mailbox is misconfigured.
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
// `detail` is for the panel status (mailAdapter), not for end users.
return { detail: (err as Error).message, error: 'Failed to send email.', sent: false }
return { detail: (err as Error).message, error: 'The e-mail was not sent.', sent: false }
}
},
})
+3 -3
View File
@@ -60,12 +60,12 @@ export async function sendEmail({
const pass = smtp.smtpPassword
if (!host || !user || !pass) {
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
return { error: 'Fill in the server, user name and password.', sent: false }
}
const fromAddress = from ?? smtp.smtpFromAddress
if (!fromAddress) {
return { error: 'No from-address configured.', sent: false }
return { error: 'Fill in the sender address.', sent: false }
}
const fromName = smtp.smtpFromName
@@ -90,6 +90,6 @@ export async function sendEmail({
return { messageId: info.messageId, sent: true }
} catch (err) {
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
return { error: 'Failed to send email.', sent: false }
return { error: 'The e-mail was not sent.', sent: false }
}
}
+36 -17
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import { addDataAndFileToRequest } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
/**
* Custom endpoint: send a test email to a given address through whatever
@@ -17,56 +18,74 @@ import { userMeetsRole } from '../../access/predicates.js'
* Returns the adapter's own result so the panel can show exactly what happened,
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
*/
/** The site name from Site settings (in the request's locale), or '' when unavailable. */
async function siteName(req: PayloadRequest): Promise<string> {
try {
const doc = (await req.payload.findGlobal({ slug: 'site-settings' as never, depth: 0, req })) as { siteName?: unknown }
return typeof doc?.siteName === 'string' ? doc.siteName.trim() : ''
} catch {
return ''
}
}
const escapeHtml = (v: string) =>
v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
export const testEmailEndpoint: Endpoint = {
handler: async (req: PayloadRequest) => {
// Messages in the language of the admin user who clicked the button.
const i18n = req.i18n as Parameters<typeof serverText>[0]
// Auth: only admins may trigger a send — the same gate as the
// SiteIntegrations global that holds the transport settings.
if (!req.user) {
return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 })
return Response.json({ error: serverText(i18n, 'testEmailLoggedOut'), ok: false }, { status: 401 })
}
if (!userMeetsRole(req, 'admin')) {
return Response.json({ error: 'Forbidden', ok: false }, { status: 403 })
return Response.json({ error: serverText(i18n, 'testEmailForbidden'), ok: false }, { status: 403 })
}
await addDataAndFileToRequest(req)
const to = (req.data?.to as string | undefined)?.trim()
if (!to || !/^[^@\s]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(to)) {
return Response.json(
{ error: 'Provide a valid recipient address.', ok: false },
{ status: 400 },
)
return Response.json({ error: serverText(i18n, 'testEmailInvalidRecipient'), ok: false }, { status: 400 })
}
const site = await siteName(req)
const subject = site ? serverText(i18n, 'testEmailSubject', { site }) : serverText(i18n, 'testEmailSubjectGeneric')
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
try {
const info = await req.payload.sendEmail({
html: '<p>This is a test message from <strong>ipal-kit</strong>. If you received it, outbound email is configured correctly.</p>',
subject: 'ipal-kit — test email',
text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.',
html: `<p>${escapeHtml(text)}</p>`,
subject,
text,
to,
})
// Payload's sendEmail resolves with the adapter's result. Our adapters
// return { sent: boolean, error?: string }; nodemailer returns info with
// messageId. Normalize to a simple ok/message for the panel.
// return { sent: boolean, error?: string, code?: string }; nodemailer
// returns info with messageId. Normalize to a simple ok/message for the panel.
const sent =
info && typeof info === 'object' && 'sent' in info
? (info as { sent?: boolean }).sent !== false
: true
if (!sent) {
const error = (info as { error?: string })?.error ?? 'Send failed (see server logs).'
const failed = info as { code?: string; detail?: string; error?: string }
req.payload.logger.error(`[ipal] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
const error =
failed?.code === 'not-configured'
? serverText(i18n, 'testEmailNotConfigured')
: serverText(i18n, 'testEmailFailed')
return Response.json({ error, ok: false }, { status: 502 })
}
return Response.json({ message: `Test email sent to ${to}.`, ok: true })
return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] Test email failed: ${message}`)
return Response.json(
{ error: 'Send failed. Check transport settings and server logs.', ok: false },
{ status: 502 },
)
return Response.json({ error: serverText(i18n, 'testEmailFailed'), ok: false }, { status: 502 })
}
},
method: 'post',
+80 -31
View File
@@ -13,7 +13,7 @@ import type { Block, Field } from 'payload'
* 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 /
* Labels in English and Polish. Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
@@ -23,41 +23,69 @@ import type { Block, Field } from 'payload'
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
admin: {
description: { en: 'No spaces, e.g. services.', pl: 'Bez spacji, np. uslugi.' },
width: '50%',
},
label: { en: 'Field key', pl: 'Klucz pola' },
required: true,
}
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: { en: 'Label', pl: 'Etykieta' }, localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: { en: 'Width (%)', pl: 'Szerokość (%)' } }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: { en: 'Required', pl: 'Wymagane' } }
/**
* "Show only when": the field — or, on a Step, the whole step — appears only
* when another field has one of the given values. Evaluated by visibleFields
* in the browser and again on the server (hidden fields are neither required nor stored).
*
* The named group keeps the data at `showWhen.field` / `showWhen.values`; its
* heading is hidden and a collapsible inside it (presentation only) carries
* the label, collapsed by default.
*/
export const showWhenField: Field = {
name: 'showWhen',
type: 'group',
admin: {
description:
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
},
admin: { hideGutter: true },
fields: [
{
type: 'row',
type: 'collapsible',
admin: {
description: {
en: 'Leave empty to always show it.',
pl: 'Zostaw puste, aby zawsze było widoczne.',
},
initCollapsed: true,
},
fields: [
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
{
name: 'values',
type: 'text',
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
label: 'Values',
type: 'row',
fields: [
{
name: 'field',
type: 'text',
admin: { description: { en: 'Key of the field it depends on.', pl: 'Klucz pola, od którego zależy.' }, width: '50%' },
label: { en: 'Field key', pl: 'Klucz pola' },
},
{
name: 'values',
type: 'text',
admin: {
description: {
en: 'Separate with commas; leave empty for any value.',
pl: 'Oddziel przecinkami; zostaw puste dla dowolnej wartości.',
},
width: '50%',
},
label: { en: 'Values', pl: 'Wartości' },
},
],
},
],
label: { en: 'Show only when', pl: 'Pokaż tylko, gdy' },
},
],
label: 'Show only when',
label: false,
}
/** Adds "Show only when" at the end of a block's fields. */
@@ -69,8 +97,11 @@ export function withShowWhen<B extends Block>(block: B): B {
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',
admin: {
description: { en: 'Example shown inside the empty field.', pl: 'Przykład widoczny w pustym polu.' },
placeholder: { en: 'e.g. 10:00–12:00', pl: 'np. 10:00–12:00' },
},
label: { en: 'Placeholder', pl: 'Tekst podpowiedzi' },
localized: true,
}
@@ -85,7 +116,7 @@ const timeBase: Block = {
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
],
labels: { plural: 'Times', singular: 'Time' },
labels: { plural: { en: 'Time fields', pl: 'Pola godziny' }, singular: { en: 'Time', pl: 'Godzina' } },
}
const stepBase: Block = {
@@ -95,15 +126,17 @@ const stepBase: Block = {
name: 'title',
type: 'text',
admin: {
description:
'Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.',
description: {
en: 'Starts a new step with the fields below it, up to the next step.',
pl: 'Zaczyna nowy krok z polami poniżej, aż do następnego kroku.',
},
},
label: 'Step title',
label: { en: 'Step title', pl: 'Tytuł kroku' },
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: { en: 'Step description', pl: 'Opis kroku' }, localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
labels: { plural: { en: 'Steps', pl: 'Kroki' }, singular: { en: 'Step', pl: 'Krok' } },
}
const checkboxGroupBase: Block = {
@@ -118,23 +151,39 @@ const checkboxGroupBase: Block = {
{
type: 'row',
fields: [
{ name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: 'Value', required: true },
{ name: 'label', type: 'text', admin: { width: '50%' }, label: { en: 'Label', pl: 'Etykieta' }, localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: { en: 'Value', pl: 'Wartość' }, required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
label: { en: 'Options', pl: 'Opcje' },
labels: { plural: { en: 'Options', pl: 'Opcje' }, singular: { en: 'Option', pl: 'Opcja' } },
minRows: 1,
},
{
type: 'row',
fields: [
{ name: 'minSelected', type: 'number', admin: { description: 'Empty = no minimum (Required = at least one).', width: '50%' }, label: 'Minimum selected', min: 0 },
{ name: 'maxSelected', type: 'number', admin: { description: 'Empty = no limit.', width: '50%' }, label: 'Maximum selected', min: 1 },
{
name: 'minSelected',
type: 'number',
admin: { description: { en: 'Leave empty for no minimum.', pl: 'Zostaw puste, aby nie ustalać minimum.' }, width: '50%' },
label: { en: 'Minimum selected', pl: 'Minimum zaznaczonych' },
min: 0,
},
{
name: 'maxSelected',
type: 'number',
admin: { description: { en: 'Leave empty for no limit.', pl: 'Zostaw puste, aby nie ustalać limitu.' }, width: '50%' },
label: { en: 'Maximum selected', pl: 'Maksimum zaznaczonych' },
min: 1,
},
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
labels: {
plural: { en: 'Multiple choice fields', pl: 'Pola wielokrotnego wyboru' },
singular: { en: 'Multiple choice', pl: 'Wielokrotny wybór' },
},
}
export const stepBlock: Block = withShowWhen(stepBase)
+29 -7
View File
@@ -114,7 +114,7 @@ ${footerLines ? `<tr><td class="ipal-pad" style="padding:20px 36px 28px;backgrou
</table></td></tr></table></body></html>`
}
/** Site Settings → "Emails" tab (shown with `forms: { emailLayout: true }`). */
/** Site settings → "E-mails" tab (shown with `forms: { emailLayout: true }`). */
export const emailSettingsFields: Field[] = [
{
name: 'email',
@@ -124,18 +124,40 @@ export const emailSettingsFields: Field[] = [
{
name: 'logo',
type: 'upload',
admin: { description: 'PNG or JPG for a light background — Gmail and Outlook do not show SVG. Empty = the site name.' },
label: 'E-mail logo',
admin: {
description: {
en: 'PNG or JPG on a light background, as many e-mail apps do not show SVG; leave empty to show the site name.',
pl: 'PNG lub JPG na jasnym tle, bo wiele programów pocztowych nie wyświetla SVG; zostaw puste, aby pokazać nazwę witryny.',
},
},
label: { en: 'E-mail logo', pl: 'Logo w e-mailach' },
relationTo: 'media',
},
{
name: 'accentColor',
type: 'text',
admin: { description: 'Hex, e.g. #017BD0 — top bar and section titles.' },
label: 'Accent colour',
validate: (value: unknown) => !value || /^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) || 'Use a hex colour, e.g. #017BD0.',
admin: {
description: {
en: 'Used for the top bar and section titles.',
pl: 'Używany na górnym pasku i w tytułach sekcji.',
},
placeholder: '#017BD0',
},
label: { en: 'Accent colour', pl: 'Kolor akcentu' },
validate: (value: unknown, { req }: { req?: { i18n?: { language?: string } } } = {}) =>
!value ||
/^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) ||
(req?.i18n?.language === 'pl' ? 'Wpisz kolor w formacie HEX, np. #017BD0.' : 'Enter a hex colour, e.g. #017BD0.'),
},
{
name: 'footer',
type: 'textarea',
admin: {
description: { en: 'E.g. company name and address.', pl: 'Np. nazwa i adres firmy.' },
},
label: { en: 'Footer', pl: 'Stopka' },
localized: true,
},
{ name: 'footer', type: 'textarea', admin: { description: 'E.g. company name and address.' }, label: 'Footer', localized: true },
],
label: false,
},
+15 -11
View File
@@ -25,35 +25,39 @@ export function buildFormAnalyticsFields(): Field[] {
name: 'analytics',
type: 'group',
admin: {
description:
'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.',
description: {
en: 'Sent to Google Tag Manager after a successful submission.',
pl: 'Wysyłane do Google Tag Manager po udanym wysłaniu formularza.',
},
},
fields: [
{
name: 'event',
type: 'text',
admin: {
description:
'Empty = nothing is pushed. Default "form_submit" — attach your GTM trigger to it.',
description: { en: 'Leave empty to send nothing.', pl: 'Zostaw puste, aby nic nie wysyłać.' },
},
defaultValue: 'form_submit',
label: 'Event name',
label: { en: 'Event name', pl: 'Nazwa zdarzenia' },
},
{
name: 'params',
type: 'array',
admin: {
description:
'Key/value pairs sent with the event. A value starting with "$" is taken from a form field, e.g. $topic → the chosen topic.',
description: {
en: 'A value starting with $ is taken from a form field, e.g. $topic.',
pl: 'Wartość zaczynająca się od $ pochodzi z pola formularza, np. $topic.',
},
},
fields: [
{ name: 'key', type: 'text', required: true },
{ name: 'value', type: 'text', required: true },
{ name: 'key', type: 'text', label: { en: 'Key', pl: 'Klucz' }, required: true },
{ name: 'value', type: 'text', label: { en: 'Value', pl: 'Wartość' }, required: true },
],
label: 'Event parameters',
label: { en: 'Event parameters', pl: 'Parametry zdarzenia' },
labels: { plural: { en: 'Parameters', pl: 'Parametry' }, singular: { en: 'Parameter', pl: 'Parametr' } },
},
],
label: 'Analytics (GTM / dataLayer)',
label: { en: 'Analytics event', pl: 'Zdarzenie analityki' },
},
]
}
+142 -4
View File
@@ -3,6 +3,7 @@ import type { Block, Field, Plugin } from 'payload'
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { AdminText } from '../admin-i18n/define.js'
import type { FormsOption } from './types.js'
import { userMeetsRole } from '../access/predicates.js'
@@ -11,6 +12,139 @@ import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
/**
* Panel wording for form-builder's own fields, by its translation key. Its
* labels are functions (`({ t }) => t('plugin-form-builder:name')`); these
* replace them with `{ en, pl }` text — labels only, names and data unchanged.
* Keys not listed keep form-builder's own text.
*/
const FORM_BUILDER_TEXTS: Record<string, AdminText> = {
name: { en: 'Field key', pl: 'Klucz pola' },
bcc: { en: 'BCC', pl: 'UDW' },
cc: { en: 'CC', pl: 'DW' },
checkboxPlural: { en: 'Checkboxes', pl: 'Pola wyboru' },
checkboxSingular: { en: 'Checkbox', pl: 'Pole wyboru' },
checkedByDefault: { en: 'Checked by default', pl: 'Domyślnie zaznaczone' },
chooseConfirmationType: {
en: 'Show a message or go to another page after the form is sent.',
pl: 'Pokaż komunikat lub przejdź na inną stronę po wysłaniu formularza.',
},
confirmationMessage: { en: 'Confirmation message', pl: 'Komunikat potwierdzenia' },
confirmationType: { en: 'After sending', pl: 'Po wysłaniu' },
countryPlural: { en: 'Country fields', pl: 'Pola kraju' },
countrySingular: { en: 'Country', pl: 'Kraj' },
customURL: { en: 'Address (URL)', pl: 'Adres (URL)' },
datePlural: { en: 'Date fields', pl: 'Pola daty' },
dateSingular: { en: 'Date', pl: 'Data' },
defaultValue: { en: 'Default value', pl: 'Wartość domyślna' },
documentToLinkTo: { en: 'Page', pl: 'Strona' },
emailFrom: { en: 'From', pl: 'Od' },
emailPlural: { en: 'E-mail fields', pl: 'Pola e-mail' },
emailsDescription: {
en: 'Sent after each submission; use {{email}} for a field value and {{*:table}} for all values.',
pl: 'Wysyłane po każdym zgłoszeniu; {{email}} wstawia wartość pola, a {{*:table}} wszystkie wartości.',
},
emailSingular: { en: 'E-mail', pl: 'E-mail' },
emailTo: { en: 'To', pl: 'Do' },
field: { en: 'Field', pl: 'Pole' },
fields: { en: 'Fields', pl: 'Pola' },
fieldWidth: { en: 'Width (%)', pl: 'Szerokość (%)' },
internalLink: { en: 'Page', pl: 'Strona' },
label: { en: 'Label', pl: 'Etykieta' },
message: { en: 'Message', pl: 'Wiadomość' },
messageDescription: { en: 'Text of the e-mail.', pl: 'Treść wiadomości e-mail.' },
messagePlural: { en: 'Text blocks', pl: 'Bloki tekstu' },
messageSingular: { en: 'Text block', pl: 'Blok tekstu' },
numberPlural: { en: 'Number fields', pl: 'Pola liczbowe' },
numberSingular: { en: 'Number', pl: 'Liczba' },
optionPlural: { en: 'Options', pl: 'Opcje' },
optionSingular: { en: 'Option', pl: 'Opcja' },
placeholder: { en: 'Placeholder', pl: 'Tekst podpowiedzi' },
radioOptions: { en: 'Options', pl: 'Opcje' },
radioPlural: { en: 'Single choice fields', pl: 'Pola jednokrotnego wyboru' },
radioSingular: { en: 'Single choice', pl: 'Jednokrotny wybór' },
redirect: { en: 'Redirect', pl: 'Przekierowanie' },
replyTo: { en: 'Reply to', pl: 'Odpowiedź do' },
required: { en: 'Required', pl: 'Wymagane' },
selectOptions: { en: 'Options', pl: 'Opcje' },
selectPlural: { en: 'Dropdown fields', pl: 'Listy rozwijane' },
selectSingular: { en: 'Dropdown', pl: 'Lista rozwijana' },
statePlural: { en: 'Region fields', pl: 'Pola regionu' },
stateSingular: { en: 'Region', pl: 'Region' },
subject: { en: 'Subject', pl: 'Temat' },
submitButton: { en: 'Button text', pl: 'Tekst przycisku' },
textareaPlural: { en: 'Long text fields', pl: 'Pola długiego tekstu' },
textareaSingular: { en: 'Long text', pl: 'Długi tekst' },
textPlural: { en: 'Text fields', pl: 'Pola tekstowe' },
textSingular: { en: 'Text', pl: 'Tekst' },
title: { en: 'Title', pl: 'Tytuł' },
urlToRedirectTo: { en: 'Address (URL)', pl: 'Adres (URL)' },
value: { en: 'Value', pl: 'Wartość' },
}
/** `({ t }) => t('plugin-form-builder:<key>')` → our `{ en, pl }`; anything else unchanged. */
function formBuilderText<V>(value: V): AdminText | V {
if (typeof value !== 'function') {return value}
try {
const key = String((value as (args: unknown) => unknown)({ i18n: {}, t: (k: string) => k }))
return FORM_BUILDER_TEXTS[key.replace(/^plugin-form-builder:/, '')] ?? value
} catch {
return value
}
}
/** Replaces form-builder's labels, descriptions and option labels, deep (blocks, arrays, rows, groups). */
function localizeFormBuilder<T>(node: T): T {
if (Array.isArray(node)) {return node.map(localizeFormBuilder) as T}
if (!node || typeof node !== 'object') {return node}
const f = node as Record<string, unknown>
const out: Record<string, unknown> = { ...f }
if ('label' in f) {out.label = formBuilderText(f.label)}
// The text block's rich text has no label of its own.
if (f.type === 'richText' && f.name === 'message' && !f.label) {out.label = { en: 'Text', pl: 'Treść' }}
if (f.labels && typeof f.labels === 'object') {
const labels = f.labels as Record<string, unknown>
out.labels = { ...labels, plural: formBuilderText(labels.plural), singular: formBuilderText(labels.singular) }
}
if (f.admin && typeof f.admin === 'object' && 'description' in f.admin) {
const admin = f.admin as Record<string, unknown>
out.admin = { ...admin, description: formBuilderText(admin.description) }
}
if (Array.isArray(f.options)) {out.options = f.options.map((o) => (o && typeof o === 'object' ? { ...o, label: formBuilderText((o as { label?: unknown }).label) } : o))}
for (const key of ['fields', 'blocks', 'tabs'] as const) {
if (Array.isArray(f[key])) {out[key] = localizeFormBuilder(f[key])}
}
return out as T
}
/** Labels for the submission fields form-builder leaves unlabelled. */
const SUBMISSION_LABELS: Record<string, AdminText> = {
form: { en: 'Form', pl: 'Formularz' },
submissionData: { en: 'Answers', pl: 'Odpowiedzi' },
submissionUploads: { en: 'Files', pl: 'Pliki' },
}
const SUBMISSION_ROW_LABELS: Record<string, AdminText> = {
field: { en: 'Field key', pl: 'Klucz pola' },
value: { en: 'Value', pl: 'Wartość' },
}
function labelSubmissionFields(fields: Field[]): Field[] {
return fields.map((field) => {
if (!('name' in field) || !SUBMISSION_LABELS[field.name] || field.label) {return field}
const labelled = { ...field, label: SUBMISSION_LABELS[field.name] } as Field
if (labelled.type === 'array') {
return {
...labelled,
fields: labelled.fields.map((sub) =>
'name' in sub && SUBMISSION_ROW_LABELS[sub.name] && !sub.label ? ({ ...sub, label: SUBMISSION_ROW_LABELS[sub.name] } as Field) : sub,
),
labels: labelled.labels ?? { plural: { en: 'Answers', pl: 'Odpowiedzi' }, singular: { en: 'Answer', pl: 'Odpowiedź' } },
} as Field
}
return labelled
})
}
/** 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)
@@ -65,7 +199,7 @@ function hideEmails(fields: Field[]): Field[] {
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const adminGroup = forms.adminGroup === undefined ? { en: 'Forms', pl: 'Formularze' } : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
const beforeEmail: BeforeEmail | undefined =
@@ -109,7 +243,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
// Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar.
formOverrides: {
labels: { plural: 'Forms', singular: 'Form' },
labels: { plural: { en: 'Forms', pl: 'Formularze' }, singular: { en: 'Form', pl: 'Formularz' } },
...forms.formOverrides,
access: {
create: staffAccess,
@@ -120,12 +254,12 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
},
admin: { ...group, ...forms.formOverrides?.admin },
fields: ({ defaultFields }) => {
const protectedFields = hideEmails(defaultFields)
const protectedFields = hideEmails(localizeFormBuilder(defaultFields))
return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields
},
},
formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' },
labels: { plural: { en: 'Submissions', pl: 'Zgłoszenia' }, singular: { en: 'Submission', pl: 'Zgłoszenie' } },
...forms.formSubmissionOverrides,
access: {
create: submissionsCreateAccess,
@@ -134,6 +268,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
...forms.formSubmissionOverrides?.access,
},
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
fields: ({ defaultFields }) => {
const labelled = labelSubmissionFields(defaultFields)
return forms.formSubmissionOverrides?.fields ? forms.formSubmissionOverrides.fields({ defaultFields: labelled }) : labelled
},
},
})
}
+4 -1
View File
@@ -31,9 +31,12 @@ export {
custom,
email,
isEmail,
localizedRules,
maxLength,
minLength,
pattern,
required,
VALIDATION_MESSAGES,
validationMessages,
} from './validators.js'
export type { Rule } from './validators.js'
export type { Rule, ValidationMessages } from './validators.js'
+24
View File
@@ -67,6 +67,8 @@ export type SubmitFailure =
field?: string
/** What was wrong with it. */
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
label?: string
reason: 'validation'
success: false
}
@@ -141,11 +143,13 @@ export async function submitForm({
if (validation.reason === 'consent') {
return { field: validation.field, reason: 'consent', success: false }
}
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
return {
reason: 'validation',
success: false,
...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}),
...(label ? { label } : {}),
}
}
@@ -170,3 +174,23 @@ export async function submitForm({
return { reason: 'error', success: false }
}
}
/**
* The label of one form field in the page's language, so a message names the
* field the way the visitor sees it ("E-mail address", not "email"). Only read
* when a submission fails; never throws.
*/
async function fieldLabel(payload: BasePayload, formId: string, name: string, locale?: string): Promise<string | undefined> {
try {
const form = (await payload.findByID({
id: formId,
collection: 'forms',
depth: 0,
...(locale ? { locale: locale as never } : {}),
})) as { fields?: { label?: unknown; name?: unknown }[] }
const label = form.fields?.find((f) => f.name === name)?.label
return typeof label === 'string' && label.trim() ? label.trim() : undefined
} catch {
return undefined
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ export type FormsOption = {
* `false` = Payload default ("Collections"). An explicit `admin.group` in
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: false | string
adminGroup?: false | Record<string, string> | string
/**
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
* the ipal layout when `emailLayout` is on.
+6 -2
View File
@@ -61,10 +61,14 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
const shown = new Set(visibleInputs(values).map((field) => field.name))
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
else if (result.field) {
// No message from the server → name the field by its label, as the visitor sees it.
const label = fields.find((field) => field.name === result.field)?.label || result.field
serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', label) }
}
return result
},
[action, texts.validation, visibleInputs],
[action, fields, texts.validation, visibleInputs],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
+8 -4
View File
@@ -26,7 +26,10 @@ export type Validator<T> = (values: T) => FormErrors<T>
type UseFormOptions<T extends Record<string, unknown>> = {
/** Clear a field's error as soon as the user edits it. Default true. */
clearErrorOnChange?: boolean
/** Generic error message shown when the action fails/throws with no message. */
/**
* Generic error shown when the action fails or throws without a message.
* Pass one in the page's language (e.g. getNotificationTexts(...).form.error).
*/
errorFallback?: string
/** Defines the field set AND the reset state. Any shape you like. */
initialValues: T
@@ -73,7 +76,7 @@ type UseFormOptions<T extends Record<string, unknown>> = {
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
const {
clearErrorOnChange = true,
errorFallback = 'Something went wrong. Please try again.',
errorFallback = 'The form could not be sent. Please try again in a moment.',
initialValues,
requireTurnstile = false,
submitAction,
@@ -144,8 +147,9 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
} else {
setErrorMessage(result.message || errorFallback)
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback)
} catch {
// Never show the thrown error's text to a visitor — it can carry server internals.
setErrorMessage(errorFallback)
} finally {
setIsSubmitting(false)
}
+70 -6
View File
@@ -31,9 +31,54 @@ const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Standalone e-mail check, handy outside the rule system too. */
export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())
/**
* Default rule messages, per language. English is used unless a rule gets its
* own message; `localizedRules('pl')` builds the same rules with the Polish
* set (any other language falls back to English).
*/
export type ValidationMessages = {
checked: string
email: string
maxLength: (n: number) => string
minLength: (n: number) => string
pattern: string
required: string
}
/** Polish plural of "znak" (character): 1 znak, 2–4 znaki, 5+ znaków. */
const znaki = (n: number) => {
const form = new Intl.PluralRules('pl').select(n)
return form === 'one' ? 'znak' : form === 'few' ? 'znaki' : 'znaków'
}
export const VALIDATION_MESSAGES: { en: ValidationMessages; pl: ValidationMessages } = {
en: {
checked: 'Tick this box to continue.',
email: 'Enter a valid e-mail address, e.g. [email protected].',
maxLength: (n) => `Enter no more than ${n} ${n === 1 ? 'character' : 'characters'}.`,
minLength: (n) => `Enter at least ${n} ${n === 1 ? 'character' : 'characters'}.`,
pattern: 'Check the format of this field.',
required: 'Fill in this field.',
},
pl: {
checked: 'Zaznacz to pole, aby kontynuować.',
email: 'Wpisz poprawny adres e-mail, np. [email protected].',
maxLength: (n) => `Wpisz najwyżej ${n} ${znaki(n)}.`,
minLength: (n) => `Wpisz co najmniej ${n} ${znaki(n)}.`,
pattern: 'Sprawdź format tego pola.',
required: 'Uzupełnij to pole.',
},
}
/** The message set for a page language ('pl', 'pl-PL' → Polish; anything else → English). */
export const validationMessages = (locale?: string): ValidationMessages =>
locale?.toLowerCase().startsWith('pl') ? VALIDATION_MESSAGES.pl : VALIDATION_MESSAGES.en
const EN = VALIDATION_MESSAGES.en
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
export const required =
(msg = 'required'): Rule =>
(msg = EN.required): Rule =>
(v) => {
if (v == null) {return msg}
if (typeof v === 'string' && !v.trim()) {return msg}
@@ -42,32 +87,51 @@ export const required =
}
export const email =
(msg = 'invalid email'): Rule =>
(msg = EN.email): Rule =>
(v) =>
isEmail(v) ? true : msg
export const minLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`)
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? EN.minLength(n))
export const maxLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`)
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? EN.maxLength(n))
/** Checkbox must be ticked (true). */
export const checked =
(msg = 'required'): Rule =>
(msg = EN.checked): Rule =>
(v) =>
v === true ? true : msg
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export const pattern =
(re: RegExp, msg = 'invalid format'): Rule =>
(re: RegExp, msg = EN.pattern): Rule =>
(v) =>
typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg
/**
* The rules with default messages in the page's language. A message passed to
* a rule still wins:
*
* const r = localizedRules(locale)
* buildValidator({ email: [r.required(), r.email()], message: [r.minLength(10)] })
*/
export function localizedRules(locale?: string) {
const m = validationMessages(locale)
return {
checked: (msg?: string) => checked(msg ?? m.checked),
email: (msg?: string) => email(msg ?? m.email),
maxLength: (n: number, msg?: string) => maxLength(n, msg ?? m.maxLength(n)),
minLength: (n: number, msg?: string) => minLength(n, msg ?? m.minLength(n)),
pattern: (re: RegExp, msg?: string) => pattern(re, msg ?? m.pattern),
required: (msg?: string) => required(msg ?? m.required),
}
}
/** Escape hatch: any predicate → rule. */
export const custom =
(test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string): Rule =>
+8 -3
View File
@@ -2,11 +2,14 @@ import type { CollectionBeforeDeleteHook } from 'payload'
import { APIError } from 'payload'
import { settingsFieldLabel } from './validateUniqueRole.js'
/**
* Blocks deletion of a page assigned a System Page role (homepage,
* privacyPolicy, cookiePolicy, termsOfService). An editor deleting the privacy
* policy or homepage by accident would break routing and compliance links; this
* stops it with a clear error. They must unassign the role first (deliberate).
* stops it with a clear error in the editor's admin language, naming the role by
* its field label. They must unassign the role first (deliberate).
*
* Reads the role assignments from SiteSettings (which page holds which role).
*
@@ -34,9 +37,11 @@ export function buildPreventDeleteSystemPage(
const assignedId =
assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned
if ((typeof assignedId === 'string' || typeof assignedId === 'number') && String(assignedId) === String(id)) {
const label = settingsFieldLabel(req, field, { settingsSlug })
throw new APIError(
`Cannot delete a page assigned to the system role "${field}". ` +
`Detach the role in Site Settings first.`,
req.i18n?.language === 'pl'
? `Tej strony nie można usunąć, bo jest ustawiona jako „${label}” w ustawieniach witryny. Najpierw wybierz tam inną stronę.`
: `This page is set as “${label}” in Site settings, so it cannot be deleted. Choose another page there first.`,
400,
)
}
+58 -6
View File
@@ -1,31 +1,83 @@
import type { FieldHook } from 'payload'
import type { FieldHook, PayloadRequest } from 'payload'
import { APIError } from 'payload'
type FieldLike = { fields?: FieldLike[]; label?: unknown; name?: string; tabs?: FieldLike[]; type?: string }
/** Finds a field by name in data that stays flat: rows, collapsibles and unnamed tabs only. */
function findFlatField(fields: readonly FieldLike[] | undefined, name: string): FieldLike | undefined {
for (const field of fields ?? []) {
if (field.name === name && field.type !== 'tabs') {return field}
if (field.type === 'tabs') {
for (const tab of field.tabs ?? []) {
if (tab.name) {continue}
const hit = findFlatField(tab.fields, name)
if (hit) {return hit}
}
} else if ((field.type === 'row' || field.type === 'collapsible') && field.fields) {
const hit = findFlatField(field.fields, name)
if (hit) {return hit}
}
}
return undefined
}
/** A field label as the editor sees it, in the admin language; the field name when there is none. */
export function labelInLanguage(label: unknown, language: string | undefined, fallback: string): string {
if (typeof label === 'string' && label) {return label}
if (label && typeof label === 'object') {
const map = label as Record<string, unknown>
const text = (language ? map[language] : undefined) ?? map.en ?? Object.values(map).find((v) => typeof v === 'string')
if (typeof text === 'string' && text) {return text}
}
return fallback
}
/**
* The visible label of a Site Settings field (e.g. "Privacy policy" for
* `privacyPolicy`) in the request's admin language. Reads it from the given
* fields, or from the global in the Payload config; falls back to the name.
*/
export function settingsFieldLabel(
req: Partial<PayloadRequest> | undefined,
name: string,
{ fields, settingsSlug = 'site-settings' }: { fields?: readonly unknown[]; settingsSlug?: string } = {},
): string {
const source =
fields ?? (req?.payload?.config?.globals?.find((g) => g.slug === settingsSlug)?.fields as readonly unknown[] | undefined)
const field = findFlatField(source as FieldLike[] | undefined, name)
return labelInLanguage(field?.label, req?.i18n?.language, name)
}
/**
* Field hook for a System Page role relationship in SiteSettings: ensures a page
* isn't assigned to two roles at once (e.g. the same page as both homepage and
* privacyPolicy), which would make routing ambiguous.
*
* Attach to each role field's beforeValidate. `siblingFields` are the OTHER role
* field names to check against.
* field names to check against. The error names both fields by their labels in
* the editor's admin language.
*
* hooks: { beforeValidate: [buildValidateUniqueRole({
* siblingFields: ['privacyPolicy', 'cookiePolicy', 'termsOfService'],
* })] }
*/
export function buildValidateUniqueRole(args: { siblingFields: string[] }): FieldHook {
return ({ field, siblingData, value }) => {
return ({ field, global, req, siblingData, value }) => {
if (value == null) {return value}
const thisId = typeof value === 'object' ? (value as { id?: unknown }).id : value
for (const sibling of args.siblingFields) {
const other = (siblingData as Record<string, unknown>)?.[sibling]
const otherId = other && typeof other === 'object' ? (other as { id?: unknown }).id : other
if ((typeof otherId === 'string' || typeof otherId === 'number') && String(otherId) === String(thisId)) {
const name = typeof field === 'object' && 'name' in field ? field.name : 'ta rola'
const language = req?.i18n?.language
const name = (typeof field === 'object' && 'name' in field ? field.name : '') ?? ''
const thisLabel = labelInLanguage(typeof field === 'object' ? field.label : undefined, language, name)
const otherLabel = settingsFieldLabel(req, sibling, global?.fields ? { fields: global.fields } : {})
throw new APIError(
`Ta sama strona jest przypisana do "${name}" i "${sibling}". ` +
`Każda rola systemowa musi wskazywać inną stronę.`,
language === 'pl'
? `Ta sama strona jest ustawiona jako „${thisLabel}” i „${otherLabel}”. Wybierz inną stronę dla każdej roli.`
: `The same page is set as “${thisLabel}” and “${otherLabel}”. Choose a different page for each.`,
400,
)
}
+31 -14
View File
@@ -2,23 +2,31 @@ import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
import { turnstileKeyProblem } from '../turnstile/config.js'
import { turnstileMissingKey } from '../turnstile/config.js'
import { type IntegrationLabel, resolveLabel, serverText, STATUS_CODE_TEXTS } from './texts.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Status groups to check: field name → label (one string, or one per language). */
checks?: Record<string, IntegrationLabel>
/** Injected by Payload into admin server components. */
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
/** Injected by Payload into admin server components. */
payload?: Payload
}
const DEFAULT_CHECKS: Record<string, IntegrationLabel> = {
emailStatus: { en: 'E-mail sending', pl: 'Wysyłka e-mail' },
turnstileStatus: { en: 'Spam protection', pl: 'Ochrona przed spamem' },
}
/**
* Dashboard alert (admin.components.beforeDashboard): lists integrations that
* are currently failing, with a link to Site Integrations. Renders nothing when
* are currently failing, with a link to Site integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing).
*/
export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emailStatus: 'Email', turnstileStatus: 'Turnstile' }, payload }: Props) {
export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, i18n, payload }: Props) {
if (!payload) {return null}
let doc: Record<string, unknown>
try {
@@ -26,17 +34,26 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
} catch {
return null
}
const i18nLike = i18n
const language = i18n?.language
const failing = Object.entries(checks)
.map(([field, label]) => {
const status = doc?.[field] as IntegrationStatus | undefined
return { label, message: status?.state === 'degraded' ? (status.message ?? status.code ?? 'error') : null }
if (status?.state !== 'degraded') {return { field, label: resolveLabel(label, language), message: null }}
const key = status.code ? STATUS_CODE_TEXTS[status.code] : undefined
const message = key ? serverText(i18nLike, key) : (status.message ?? status.code ?? serverText(i18nLike, 'alertsUnknownError'))
return { field, label: resolveLabel(label, language), message }
})
.filter((x): x is { label: string; message: string } => x.message !== null)
.filter((x): x is { field: string; label: string; message: string } => x.message !== null)
// Configuration problems no request will ever record (nothing is verified
// while Turnstile is off) — checked live from the saved keys.
const keyProblem = turnstileKeyProblem(doc ?? {})
if (keyProblem && !failing.some((f) => f.label === 'Turnstile')) {
failing.push({ label: 'Turnstile', message: keyProblem })
const missing = turnstileMissingKey(doc ?? {})
if (missing && 'turnstileStatus' in checks && !failing.some((f) => f.field === 'turnstileStatus')) {
failing.push({
field: 'turnstileStatus',
label: resolveLabel(checks.turnstileStatus, language),
message: serverText(i18nLike, missing === 'secret' ? 'statusTurnstileNoSecretKey' : 'statusTurnstileNoSiteKey'),
})
}
if (!failing.length) {return null}
@@ -51,16 +68,16 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
padding: '1rem 1.25rem',
}}
>
<strong>Integration problem — the site still works, but something needs attention.</strong>
<strong>{serverText(i18nLike, 'alertsHeading')}</strong>
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
{failing.map(({ label, message }) => (
<li key={label}>
{failing.map(({ field, label, message }) => (
<li key={field}>
<strong>{label}:</strong> {message}
</li>
))}
</ul>
<a href={`${adminRoute.replace(/\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>
Open Site Integrations →
{serverText(i18nLike, 'alertsLink')}
</a>
</div>
)
@@ -1,25 +1,27 @@
'use client'
import { useFormFields } from '@payloadcms/ui'
import { useFormFields, useTranslation } from '@payloadcms/ui'
import type { IntegrationBannerTexts } from './status.js'
import { formatDateTime, ipalT } from '../admin-i18n/t.js'
import { type IntegrationLabel, resolveLabel, STATUS_CODE_TEXTS } from './texts.js'
type Props = {
/** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string
/** Integration name shown in the banner, e.g. { en: 'Spam protection', pl: 'Ochrona przed spamem' }. */
label: IntegrationLabel
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string
}
const fmt = (iso: unknown) => {
if (typeof iso !== 'string' || !iso) {return ''}
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
/** Texts keys for this integration's failing heading and hint. */
texts?: IntegrationBannerTexts
}
/**
* Status banner on an integration's tab (Site Integrations). Shows nothing until
* Status banner on an integration's tab (Site integrations). Shows nothing until
* the integration has been used once; a red box while it's failing; a short
* green line once it works again.
* green line once it works again. Wording comes from the integration (`texts`).
*/
export function IntegrationStatusBanner({ label, statusField }: Props) {
export function IntegrationStatusBanner({ label, statusField, texts = {} }: Props) {
const { i18n, t } = useTranslation()
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
@@ -28,14 +30,28 @@ export function IntegrationStatusBanner({ label, statusField }: Props) {
if (!state) {return null}
const name = resolveLabel(label, i18n.language)
const date = (iso: unknown) => {
if (typeof iso !== 'string' || !iso || Number.isNaN(new Date(iso).getTime())) {return ''}
return formatDateTime(iso, i18n.language)
}
// Project-provided keys are not in AdminTextKey; read them through `t` the same way.
const text = (key: string, vars?: Record<string, unknown>) => ipalT(t as never, key as never, vars)
if (state === 'ok') {
const sinceText = date(since)
return (
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
✓ {sinceText ? text('statusWorkingSince', { date: sinceText, label: name }) : text('statusWorking', { label: name })}
</div>
)
}
const codeKey = code ? STATUS_CODE_TEXTS[code] : undefined
const detail = codeKey ? text(codeKey) : message
const sinceText = date(since)
const checkedText = date(checkedAt)
return (
<div
role="alert"
@@ -47,16 +63,18 @@ export function IntegrationStatusBanner({ label, statusField }: Props) {
padding: '0.9rem 1rem',
}}
>
<strong>{label} is not working — forms are accepted without this check.</strong>
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
<strong>{text(texts.failing ?? 'statusFailing', { label: name })}</strong>
{detail ? <div style={{ marginTop: '0.35rem' }}>{detail}</div> : null}
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
{code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission.
{[
code ? text('statusCode', { code }) : '',
sinceText ? text('statusSince', { date: sinceText }) : '',
checkedText ? text('statusLastChecked', { date: checkedText }) : '',
]
.filter(Boolean)
.join(' ')}
</div>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>{text(texts.hint ?? 'statusHint')}</div>
</div>
)
}
+2 -1
View File
@@ -3,4 +3,5 @@ export {
buildIntegrationStatusField,
recordIntegrationStatus,
} from './status.js'
export type { IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationBannerTexts, IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationLabel } from './texts.js'
+23 -3
View File
@@ -1,5 +1,8 @@
import type { BasePayload, Field } from 'payload'
import type { AdminTextKey } from '../admin-i18n/texts/index.js'
import type { IntegrationLabel } from './texts.js'
/**
* Health of a third-party integration (Turnstile today, SMTP/Graph later),
* stored on the SiteIntegrations global so the panel can show it:
@@ -19,7 +22,10 @@ export type IntegrationStatus = {
checkedAt?: null | string
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: null | string
/** Human explanation shown in the panel (English — panel language). */
/**
* Plain explanation for the panel, in English. Codes listed in
* STATUS_CODE_TEXTS are shown in the editor's language instead.
*/
message?: null | string
/** When the current state started. */
since?: null | string
@@ -45,15 +51,29 @@ export function buildIntegrationStatusField(name: string): Field {
}
}
/**
* Wording of the banner while the integration fails: texts keys under the
* `ipal` namespace (a project can add its own via `i18n.translations`).
* Default: a generic "<label> is not working." and "Correct the settings below and save."
*/
export type IntegrationBannerTexts = {
failing?: ({} & string) | AdminTextKey
hint?: ({} & string) | AdminTextKey
}
/** Read-only banner (UI field) — shows the status group `statusField` on the tab. */
export function buildIntegrationStatusBanner(statusField: string, label: string): Field {
export function buildIntegrationStatusBanner(
statusField: string,
label: IntegrationLabel,
texts: IntegrationBannerTexts = {},
): Field {
return {
name: `${statusField}Banner`,
type: 'ui',
admin: {
components: {
Field: {
clientProps: { label, statusField },
clientProps: { label, statusField, texts },
path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
},
},
+41
View File
@@ -0,0 +1,41 @@
import type { AdminText } from '../admin-i18n/define.js'
import type { AdminTextKey } from '../admin-i18n/texts/index.js'
import { adminTexts } from '../admin-i18n/texts/index.js'
/** A label as Payload takes it: one string, or one string per language. */
export type IntegrationLabel = AdminText | Record<string, string> | string
/** The label in `language`, falling back to English, then to any language. */
export function resolveLabel(label: IntegrationLabel | undefined, language: string | undefined): string {
if (!label) {return ''}
if (typeof label === 'string') {return label}
const map = label as Record<string, string>
return map[language ?? 'en'] ?? map.en ?? Object.values(map)[0] ?? ''
}
/** Status codes whose message has its own text — shown in the editor's language. */
export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
'bad-response': 'statusTurnstileBadResponse',
'graph-unavailable': 'statusEmailGraphUnavailable',
'internal-error': 'statusTurnstileInternalError',
'invalid-input-secret': 'statusTurnstileInvalidSecret',
'missing-input-secret': 'statusTurnstileMissingSecret',
'missing-secret': 'statusTurnstileMissingSecret',
'network-error': 'statusTurnstileNetworkError',
}
type I18nLike = { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string } | undefined
/**
* One plugin text on the server: through `i18n.t` when Payload's i18n is there
* (so a project's own translation wins), else the plugin's English text.
*/
export function serverText(i18n: I18nLike, key: AdminTextKey, vars: Record<string, unknown> = {}): string {
if (i18n?.t) {
const out = i18n.t(`ipal:${key}` as never, vars)
if (out && out !== `ipal:${key}` && out !== key) {return out}
}
const lang = i18n?.language === 'pl' ? 'pl' : 'en'
return adminTexts[lang][key].replace(/\{\{(\w+)\}\}/g, (_, name: string) => String((vars[name] as number | string | undefined) ?? ''))
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Server-safe: pure helpers and types (no React state, no DOM).
export { lightboxImage } from './lightboxImage.js'
export type { LightboxImageOptions } from './lightboxImage.js'
export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxIndex, resolveLightboxTexts } from './texts.js'
export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxIndex, resolveLightboxTexts } from './texts.js'
export type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
+21 -4
View File
@@ -2,7 +2,7 @@ import type { LightboxTexts } from './types.js'
/**
* English fallbacks, per field — the same philosophy as NOTIFICATION_FALLBACK.
* Editors translate them in Notifications → Lightbox (ipalKit `lightbox: true`).
* Editors translate them in Form messages → Image viewer (ipalKit `lightbox: true`).
*/
export const LIGHTBOX_FALLBACK: LightboxTexts = {
close: 'Close',
@@ -13,9 +13,26 @@ export const LIGHTBOX_FALLBACK: LightboxTexts = {
previous: 'Previous image',
}
/** Merges partial texts over the fallback; empty strings fall back too. */
export function resolveLightboxTexts(texts?: null | Partial<Record<keyof LightboxTexts, null | string>>): LightboxTexts {
const out = { ...LIGHTBOX_FALLBACK }
/** Polish fallbacks — used on a page whose locale is Polish. */
export const LIGHTBOX_FALLBACK_PL: LightboxTexts = {
close: 'Zamknij',
counter: '{current} / {total}',
dialog: 'Podgląd zdjęcia',
next: 'Następne zdjęcie',
open: 'Powiększ zdjęcie',
previous: 'Poprzednie zdjęcie',
}
/** Fallbacks for a page language: Polish for 'pl' / 'pl-PL', English for anything else. */
export const lightboxFallback = (locale?: string): LightboxTexts =>
locale?.toLowerCase().startsWith('pl') ? LIGHTBOX_FALLBACK_PL : LIGHTBOX_FALLBACK
/** Merges partial texts over the fallback for `locale` (English when omitted); empty strings fall back too. */
export function resolveLightboxTexts(
texts?: null | Partial<Record<keyof LightboxTexts, null | string>>,
locale?: string,
): LightboxTexts {
const out = { ...lightboxFallback(locale) }
for (const key of Object.keys(out) as (keyof LightboxTexts)[]) {
const value = texts?.[key]
if (typeof value === 'string' && value.trim()) {out[key] = value}
+40 -15
View File
@@ -1,12 +1,21 @@
import type { ArrayField, Field, GroupField } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
import { rowLabel } from '../admin-ui/rowLabel.js'
/** The default styles. A project may use any names of its own — see `appearances`. */
export type LinkAppearance = 'link' | 'primary' | 'secondary'
/** One style the editor may pick: a value (`'highlight'`) or `{ label, value }` for a friendlier panel label. */
export type LinkAppearanceOption = { label: string; value: string } | string
export type LinkAppearanceOption = { label: AdminText | string; value: string } | string
/** Panel names of the default styles, also used when a project lists them by value. */
const APPEARANCE_LABELS: Record<string, AdminText> = {
link: { en: 'Text link', pl: 'Zwykły link' },
primary: { en: 'Main button', pl: 'Przycisk główny' },
secondary: { en: 'Second button', pl: 'Przycisk dodatkowy' },
}
export type BuildLinkFieldOptions = {
/**
@@ -35,6 +44,7 @@ export type BuildLinkFieldOptions = {
}
const URL_PATTERN = /^(?:https?:\/\/|mailto:|tel:|#)/
const PAGE_LABEL = { en: 'Page', pl: 'Strona' }
type SiblingWithType = { type?: string } | undefined
@@ -71,57 +81,71 @@ export function buildLinkField({
type: 'radio',
admin: { layout: 'horizontal', width: '50%' },
defaultValue: 'internal',
label: { en: 'Link type', pl: 'Rodzaj linku' },
options: [
{ label: 'Page', value: 'internal' },
{ label: 'URL', value: 'external' },
{ label: 'File', value: 'file' },
{ label: { en: 'Page', pl: 'Strona' }, value: 'internal' },
{ label: { en: 'Address (URL)', pl: 'Adres (URL)' }, value: 'external' },
{ label: { en: 'File', pl: 'Plik' }, value: 'file' },
],
},
{
name: 'newTab',
type: 'checkbox',
admin: { style: { alignSelf: 'flex-end' }, width: '50%' },
label: 'Open in new tab',
label: { en: 'Open in new tab', pl: 'Otwórz w nowej karcie' },
},
],
},
// 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: 'page', type: 'relationship', admin: pageAdmin, label: PAGE_LABEL, relationTo, required }
: { name: 'page', type: 'relationship', admin: pageAdmin, label: PAGE_LABEL, relationTo: [...relationTo], required },
{
name: 'url',
type: 'text',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',
description: {
en: 'A full address (https://…), an e-mail (mailto:), a phone (tel:) or #section.',
pl: 'Pełny adres (https://…), e-mail (mailto:), telefon (tel:) lub #sekcja.',
},
},
label: { en: 'Address', pl: 'Adres' },
required,
validate: (v: null | string | undefined) =>
!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',
validate: (v: null | string | undefined, { req }: { req?: { i18n?: { language?: string } } } = {}) =>
!v ||
URL_PATTERN.test(v) ||
(req?.i18n?.language === 'pl'
? 'Wpisz pełny adres, np. https://example.com, albo mailto:, tel: lub #sekcja.'
: 'Enter a full address, e.g. https://example.com, or mailto:, tel: or #section.'),
},
{
name: 'file',
type: 'upload',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.',
description: {
en: 'Upload the file here instead of pasting its address.',
pl: 'Prześlij plik tutaj zamiast wklejać jego adres.',
},
},
label: { en: 'File', pl: 'Plik' },
relationTo: uploadTo,
required,
},
]
if (!disableLabel) {
fields.push({ name: 'label', type: 'text', localized: true, required })
fields.push({ name: 'label', type: 'text', label: { en: 'Link text', pl: 'Tekst linku' }, localized: true, required })
}
if (appearances && hasAppearance) {
const options = appearances.map((a) => (typeof a === 'string' ? { label: a, value: a } : a))
const options = appearances.map((a) => (typeof a === 'string' ? { label: APPEARANCE_LABELS[a] ?? a, value: a } : a))
fields.push({
name: 'appearance',
type: 'select',
defaultValue: options[0].value,
label: { en: 'Style', pl: 'Styl' },
options,
})
}
@@ -132,6 +156,7 @@ export function buildLinkField({
admin: { hideGutter: true },
fields,
interfaceName: interfaceName ?? `CmsLink${hasAppearance ? '' : 'Plain'}${disableLabel ? 'NoLabel' : ''}`,
label: { en: 'Link', pl: 'Link' },
}
}
@@ -140,7 +165,7 @@ export type BuildLinksFieldOptions = {
* What one row is called in the panel — the add button reads "Add <singular>".
* Default { singular: 'Button', plural: 'Buttons' }; e.g. { singular: 'Link', plural: 'Links' } for a link list.
*/
labels?: { plural: string; singular: string }
labels?: { plural: AdminText | string; singular: AdminText | string }
/** Max number of buttons. Default 2. */
maxRows?: number
/** Field name. Default 'links'. */
@@ -153,7 +178,7 @@ export type BuildLinksFieldOptions = {
*/
export function buildLinksField({
name = 'links',
labels = { plural: 'Buttons', singular: 'Button' },
labels = { plural: { en: 'Buttons', pl: 'Przyciski' }, singular: { en: 'Button', pl: 'Przycisk' } },
maxRows = 2,
...linkOptions
}: BuildLinksFieldOptions = {}): ArrayField {
+28 -13
View File
@@ -9,7 +9,7 @@ import { APIError } from 'payload'
* phone photo or the raw 300 MB video, and asks before touching anything.
*
* - JPG / PNG over the limits → upload is stopped with an explanation; the
* editor ticks "Optimize this upload" and saves again → converted to WebP,
* editor ticks "Optimise large image" and saves again → converted to WebP,
* resized to maxImageWidth, auto-rotated, metadata (EXIF/GPS) removed.
* - Video over maxVideoBytes → stopped with export instructions (never
* transcoded — that needs ffmpeg and minutes of CPU per file).
@@ -39,7 +39,12 @@ export type OptimizeUploadOptions = {
const OPTIMIZABLE = new Set(['image/jpeg', 'image/png'])
const MB = 1024 * 1024
const fmt = (bytes: number) => `${(bytes / MB).toFixed(1)} MB`
/** Size in MB with one decimal, in the admin language's number format. */
const fmt = (bytes: number, language: string) =>
`${new Intl.NumberFormat(language, { maximumFractionDigits: 1, minimumFractionDigits: 1 }).format(bytes / MB)} MB`
/** Label of the consent checkbox — the error messages name it. */
const CONSENT_LABEL = { en: 'Optimise large image', pl: 'Optymalizuj duży obraz' }
/**
* Consent checkbox for the upload collection's sidebar. Unticked by default;
@@ -50,12 +55,14 @@ export function buildOptimizeUploadField(name = 'optimizeOnUpload'): CheckboxFie
name,
type: 'checkbox',
admin: {
description:
'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.',
description: {
en: 'Used only for an image that is too large: makes it smaller and removes hidden photo data, such as location.',
pl: 'Działa tylko dla zbyt dużego obrazu: zmniejsza go i usuwa ukryte dane zdjęcia, np. lokalizację.',
},
position: 'sidebar',
},
defaultValue: false,
label: 'Optimize this upload',
label: CONSENT_LABEL,
}
}
@@ -91,16 +98,20 @@ export function buildOptimizeUploadHook(
if (!file) {return}
const data = (args as { data?: Record<string, unknown> }).data
const pl = req.i18n?.language === 'pl'
const lang = pl ? 'pl' : 'en'
const consent = Boolean(data?.[consentField])
const size = file.size || file.data?.length || 0
// --- Video: limit only, never transcoded ---
if (file.mimetype.startsWith('video/')) {
if (maxVideoBytes !== false && size > maxVideoBytes) {
// Export hint for the developer / log: MP4 (H.264), 720p–1080p, about 2–4 Mbit/s,
// no audio track for background videos, "web optimized" / fast start (HandBrake preset "Web").
throw new APIError(
`Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` +
'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' +
'"web optimized" / fast start enabled (e.g. HandBrake preset "Web").',
pl
? `Film ma ${fmt(size, lang)} (limit ${fmt(maxVideoBytes, lang)}). Wyeksportuj mniejszy plik, np. MP4 w 1080p, i prześlij go ponownie.`
: `The video is ${fmt(size, lang)} (limit ${fmt(maxVideoBytes, lang)}). Export a smaller file, e.g. MP4 at 1080p, and upload it again.`,
400,
undefined,
true,
@@ -134,16 +145,17 @@ export function buildOptimizeUploadHook(
if (!tooHeavy && !tooWide) {return}
const problem = [
tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null,
tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null,
tooHeavy ? `${fmt(size, lang)} (limit ${fmt(maxImageBytes, lang)})` : null,
tooWide ? (pl ? `${width} px szerokości (limit ${maxImageWidth} px)` : `${width} px wide (limit ${maxImageWidth} px)`) : null,
]
.filter(Boolean)
.join(', ')
if (!consent) {
throw new APIError(
`Image is ${problem}. Tick "Optimize this upload" in the sidebar and save again to convert it ` +
`to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`,
pl
? `Obraz ma ${problem}. Zaznacz „${CONSENT_LABEL.pl}” w panelu bocznym i zapisz ponownie albo prześlij mniejszy plik.`
: `The image is ${problem}. Tick "${CONSENT_LABEL.en}" in the sidebar and save again, or upload a smaller file.`,
400,
undefined,
true,
@@ -151,8 +163,11 @@ export function buildOptimizeUploadHook(
}
if (!sharp) {
req.payload.logger?.error?.('[ipal] Image optimisation needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.')
throw new APIError(
'Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.',
pl
? 'Optymalizacja obrazów nie jest dostępna na tym serwerze. Zapytaj administratora.'
: 'Image optimisation is not available on this server. Ask your administrator.',
500,
undefined,
true,
+27 -6
View File
@@ -1,6 +1,6 @@
import type { NotificationTexts } from './types.js'
import { LIGHTBOX_FALLBACK } from '../lightbox/texts.js'
import { LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL } from '../lightbox/texts.js'
/**
* Built-in English fallbacks, used per field when the Notifications global
@@ -10,15 +10,36 @@ import { LIGHTBOX_FALLBACK } from '../lightbox/texts.js'
export const NOTIFICATION_FALLBACK: NotificationTexts = {
form: {
back: 'Back',
consent: 'Please accept the privacy policy to continue.',
error: 'Something went wrong. Please try again later.',
consent: 'Accept the privacy policy to send the form.',
error: 'The form could not be sent. Please try again in a moment.',
next: 'Next',
notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.',
stepOf: 'Step {current} of {total}',
success: 'Thank you — your message has been sent.',
turnstile: 'Captcha verification failed. Please try again.',
validation: 'Please check the {field} field and try again.',
success: 'Thank you. Your message has been sent.',
turnstile: 'The spam protection check failed. Please try again.',
validation: 'Check the field "{field}".',
},
lightbox: LIGHTBOX_FALLBACK,
}
/** Polish fallbacks — used on a page whose locale is Polish. */
export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
form: {
back: 'Wstecz',
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
next: 'Dalej',
notFound: 'Ten formularz nie jest już dostępny.',
rateLimited: 'Zbyt wiele prób. Odczekaj chwilę i spróbuj ponownie.',
stepOf: 'Krok {current} z {total}',
success: 'Dziękujemy. Wiadomość została wysłana.',
turnstile: 'Weryfikacja ochrony przed spamem nie powiodła się. Spróbuj ponownie.',
validation: 'Sprawdź pole „{field}”.',
},
lightbox: LIGHTBOX_FALLBACK_PL,
}
/** Fallbacks for a page language: Polish for 'pl' / 'pl-PL', English for anything else. */
export const notificationFallback = (locale?: string): NotificationTexts =>
locale?.toLowerCase().startsWith('pl') ? NOTIFICATION_FALLBACK_PL : NOTIFICATION_FALLBACK
@@ -4,7 +4,7 @@ import type { NotificationsData, NotificationTexts } from './types.js'
import { resolveLightboxTexts } from '../lightbox/texts.js'
import { getGlobal } from '../payload/index.js'
import { NOTIFICATION_FALLBACK } from './defaults.js'
import { notificationFallback } from './defaults.js'
type GetNotificationTextsArgs = {
/** Active locale — selects the language variant of each text. */
@@ -13,9 +13,9 @@ type GetNotificationTextsArgs = {
}
/**
* Resolves notification texts from the Notifications global, falling back to
* English defaults per field. Mirrors getConsentTexts: one read, per-field
* fallback, locale-aware. The frontend maps a submitForm result code to the
* Resolves notification texts from the Notifications global, falling back per
* field to the defaults in the page's language (Polish for 'pl', else English).
* Mirrors getConsentTexts: one read, per-field fallback, locale-aware. The frontend maps a submitForm result code to the
* matching text and styles it however it likes (toast, inline, banner).
*/
export async function getNotificationTexts({
@@ -25,7 +25,7 @@ export async function getNotificationTexts({
const g = await getGlobal<NotificationsData>(payload, 'notifications', { locale })
const f = g.form ?? {}
const fb = NOTIFICATION_FALLBACK.form
const fb = notificationFallback(locale).form
return {
form: {
@@ -40,6 +40,6 @@ export async function getNotificationTexts({
turnstile: f.turnstile || fb.turnstile,
validation: f.validation || fb.validation,
},
lightbox: resolveLightboxTexts(g.lightbox),
lightbox: resolveLightboxTexts(g.lightbox, locale),
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
export { NOTIFICATION_FALLBACK } from './defaults.js'
export { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL, notificationFallback } from './defaults.js'
export { getNotificationTexts } from './getNotificationTexts.js'
export { resolveFormMessage } from './resolveFormMessage.js'
export type { FormNotificationTexts, NotificationsData, NotificationTexts } from './types.js'
@@ -3,7 +3,8 @@ import type { FormNotificationTexts } from './types.js'
/**
* Maps a submitForm result to the user-facing message, interpolating {field}
* for validation errors. This is the bridge the frontend uses: it gets a result
* with the field's label (its key when the form has no label) for validation
* errors. This is the bridge the frontend uses: it gets a result
* code from submitForm and the resolved texts from getNotificationTexts, and
* this turns them into one string to display. Keeping the mapping here means the
* frontend never hard-codes messages or knows about result codes.
@@ -24,9 +25,9 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormNotifica
case 'turnstile':
return texts.turnstile
case 'validation': {
// Interpolate {field} with the offending field name when present.
const field = 'field' in result && result.field ? result.field : ''
return texts.validation.replace('{field}', field)
// {field} → the label the visitor sees; no single field at fault → the generic error.
const field = result.label || result.field
return field ? texts.validation.replace('{field}', field) : texts.error
}
case 'error':
default:
+30 -17
View File
@@ -1,26 +1,41 @@
import type { Field, RelationshipField } from 'payload'
import type { AdminText } from '../admin-i18n/index.js'
import type { PagesOption, SystemPageRole } from './types.js'
import { ALL_SYSTEM_PAGE_ROLES } from './types.js'
/** Admin-facing labels per role. */
const ROLE_LABELS: Record<SystemPageRole, string> = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service',
const ROLE_LABELS: Record<SystemPageRole, AdminText> = {
cookiePolicy: { en: 'Cookie policy', pl: 'Polityka cookies' },
homepage: { en: 'Homepage', pl: 'Strona główna' },
notFound: { en: '404 page', pl: 'Strona 404' },
privacyPolicy: { en: 'Privacy policy', pl: 'Polityka prywatności' },
termsOfService: { en: 'Terms of service', pl: 'Regulamin' },
}
/** Admin descriptions per role. */
const ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound:
'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.',
/**
* Admin descriptions per role (only where the label needs one). The cookie
* banner links the privacy policy (getConsentTexts); the cookie policy and
* terms are linked by the project, e.g. with resolveSystemLinks in the footer.
*/
const ROLE_DESCRIPTIONS: Partial<Record<SystemPageRole, AdminText>> = {
cookiePolicy: {
en: 'Linked with the other legal pages, e.g. in the footer.',
pl: 'Link do niej pojawia się obok innych stron prawnych, np. w stopce.',
},
homepage: {
en: 'Shown at the main address of each language, e.g. /en.',
pl: 'Wyświetlana pod głównym adresem każdego języka, np. /pl.',
},
notFound: {
en: 'Shown for addresses that do not exist; leave empty to use the default.',
pl: 'Wyświetlana pod nieistniejącymi adresami; zostaw puste, aby użyć domyślnej wartości.',
},
privacyPolicy: {
en: 'Linked from the cookie banner and with the other legal pages.',
pl: 'Link do niej pojawia się w banerze cookies i obok innych stron prawnych.',
},
}
/**
@@ -38,9 +53,7 @@ export function buildSystemPagesFields(pages: PagesOption): Field[] {
return roles.map((role): RelationshipField => ({
name: role,
type: 'relationship',
admin: {
description: ROLE_DESCRIPTIONS[role],
},
...(ROLE_DESCRIPTIONS[role] ? { admin: { description: ROLE_DESCRIPTIONS[role] } } : {}),
label: ROLE_LABELS[role],
maxDepth: 1,
relationTo: pages.slug,
+20 -4
View File
@@ -67,14 +67,30 @@ export function extractHeadings(data: unknown, options: ExtractHeadingsOptions =
*/
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: 'show',
type: 'checkbox',
admin: {
description: {
en: 'Lists the section headings with links to them, for long pages.',
pl: 'Lista nagłówków sekcji z linkami do nich, przydatna na długich stronach.',
},
},
label: { en: 'Show table of contents', pl: 'Pokaż spis treści' },
},
{
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',
admin: {
condition: (_: unknown, s: { show?: boolean } | undefined) => Boolean(s?.show),
description: {
en: 'Heading above the list, e.g. "Contents"; leave empty for none.',
pl: 'Nagłówek nad listą, np. „Spis treści”; zostaw puste, aby go pominąć.',
},
},
label: { en: 'List heading', pl: 'Nagłówek listy' },
localized: true,
},
]
return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: 'Table of contents' }
return { name, type: 'group', fields, interfaceName: 'TableOfContentsSettings', label: { en: 'Table of contents', pl: 'Spis treści' } }
}
+9 -12
View File
@@ -1,7 +1,9 @@
'use client'
import { useConfig, useDocumentInfo, useFormFields, useLocale } from '@payloadcms/ui'
import { useConfig, useDocumentInfo, useFormFields, useLocale, useTranslation } from '@payloadcms/ui'
import { useEffect, useState } from 'react'
import { ipalT } from '../admin-i18n/t.js'
export type MetaDescriptionCheckProps = {
/** An empty description is filled from the page content on save (autoFill). */
autoFill?: boolean
@@ -39,14 +41,15 @@ export function MetaDescriptionCheck({
serverURL,
},
} = useConfig()
const { t } = useTranslation()
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' },
? { text: ipalT(t, 'seoDescEmptyAutoFill'), tone: 'info' }
: { text: ipalT(t, 'seoDescEmpty'), tone: 'warn' },
)
return
}
@@ -64,10 +67,7 @@ export function MetaDescriptionCheck({
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',
})
setWarning({ text: ipalT(t, 'seoDescSameAsSite'), tone: 'warn' })
return
}
@@ -82,10 +82,7 @@ export function MetaDescriptionCheck({
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',
})
setWarning({ text: ipalT(t, 'seoDescSameAs', { name }), tone: 'warn' })
return
}
setWarning(null)
@@ -99,7 +96,7 @@ export function MetaDescriptionCheck({
clearTimeout(timer)
controller.abort()
}
}, [api, autoFill, collectionSlug, description, id, locale, serverURL, settingsSlug, siteDescriptionField, titleField])
}, [api, autoFill, collectionSlug, description, id, locale, serverURL, settingsSlug, siteDescriptionField, t, titleField])
if (!warning) {return null}
+18 -8
View File
@@ -1,10 +1,12 @@
import type { CheckboxField, Field } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
type BuildNoindexFieldArgs = {
/** Help text under the checkbox. */
description?: string
/** Sidebar label. Default 'Exclude from indexing (noindex)'. */
label?: string
/** Help text under the checkbox: a string or `{ en, pl }`. */
description?: AdminText | string
/** Sidebar label: a string or `{ en, pl }`. Default "Hide from search engines". */
label?: AdminText | string
/** Field name for the editor-facing checkbox. Default 'noindex'. */
name?: string
/** Extend/override the generated checkbox (position, access, etc.). */
@@ -41,8 +43,11 @@ const idOf = (rel: unknown): unknown => (rel && typeof rel === 'object' ? (rel a
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
const {
name = 'noindex',
description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.',
label = 'Exclude from indexing (noindex)',
description = {
en: 'Leaves the page out of search results, the sitemap and site search.',
pl: 'Strona nie pojawi się w wynikach wyszukiwania, mapie witryny ani wyszukiwarce witryny.',
},
label = { en: 'Hide from search engines', pl: 'Ukryj przed wyszukiwarkami' },
overrides = {},
protectSystemPages = true,
settingsSlug = 'site-settings',
@@ -52,12 +57,17 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
if (!protectSystemPages || value !== true || id === undefined) {return true}
try {
const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 0, req })) as Record<string, unknown>
const pl = req.i18n?.language === 'pl'
if (idOf(settings.homepage) === id) {
return 'This page is the homepage (Site Settings → System Pages). noindex would remove the whole site from Google.'
return pl
? 'To strona główna. Ukrycie jej usunęłoby całą witrynę z wyników wyszukiwania.'
: 'This is the homepage. Hiding it would remove the whole site from search results.'
}
for (const [key, rel] of Object.entries(settings)) {
if (key.endsWith('Archive') && idOf(rel) === id) {
return 'This page is an archive (Site Settings → System Pages). noindex would hide the page that lists all its entries.'
return pl
? 'Ta strona zawiera listę wpisów sekcji. Ukrycie jej usunęłoby tę listę z wyników wyszukiwania.'
: 'This page lists the entries of a section. Hiding it would remove that list from search results.'
}
}
} catch {
+11 -6
View File
@@ -1,5 +1,7 @@
import type { Field, FieldHook, TextareaField } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { mdToPlain, truncate } from './plainText.js'
import { isAutoFillSkipped } from './skipAutoFill.js'
@@ -7,10 +9,10 @@ import { isAutoFillSkipped } from './skipAutoFill.js'
type BuildSummaryFieldArgs = {
/** Auto-fill from page content when the editor leaves it empty. Default true. */
autoFill?: boolean
/** Help text under the field. */
description?: string
/** Sidebar/admin label. */
label?: string
/** Help text under the field: a string or `{ en, pl }`. */
description?: AdminText | string
/** Sidebar label: a string or `{ en, pl }`. Default "AI summary". */
label?: AdminText | string
/** Block layout field to derive the summary from. Default 'layout'. */
layoutField?: string
/** Target length for the auto-generated summary. Default 300. */
@@ -44,8 +46,11 @@ export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {
const {
name = 'aiSummary',
autoFill = true,
description = 'Concise page description for AI agents and llms.txt (richer than the meta description). Leave empty to auto-generate from the content.',
label = 'AI summary',
description = {
en: 'Short summary for AI assistants; leave empty to create it from the page content.',
pl: 'Krótkie podsumowanie dla asystentów AI; zostaw puste, aby utworzyć je z treści strony.',
},
label = { en: 'AI summary', pl: 'Podsumowanie dla AI' },
layoutField = 'layout',
maxLength = 300,
overrides = {},
+5 -2
View File
@@ -31,14 +31,17 @@ export const indexNowFields: Field[] = [
name: KEY_FIELD,
type: 'text',
admin: {
description:
'Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.',
description: {
en: 'Created automatically; lets Bing and AI assistants learn about new pages right away.',
pl: 'Tworzony automatycznie; pozwala Bing i asystentom AI od razu poznać nowe strony.',
},
},
hooks: {
beforeChange: [
({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : randomKey()),
],
},
label: { en: 'IndexNow key', pl: 'Klucz IndexNow' },
},
]
+13 -5
View File
@@ -2,6 +2,12 @@ import type { Config, Field, TabsField } from 'payload'
import type { SeoOption } from './types.js'
const CONTENT_TAB = { en: 'Content', pl: 'Treść' }
const SEO_TAB = { en: 'SEO', pl: 'SEO' }
/** The `meta` group sits alone in the SEO tab, so its own "SEO" heading would repeat the tab name. */
const withoutHeading = (meta: Field): Field => ({ ...meta, label: false }) as Field
/**
* Wraps each SEO-enabled collection's fields into a tabbed UI: a "Content" tab
* holding the collection's own fields, and an "SEO" tab holding the `meta`
@@ -43,7 +49,7 @@ export function injectSeoTabs(config: Config, seo: SeoOption): Config {
const existingTabs = firstField
const withSeoTab: TabsField = {
...existingTabs,
tabs: [...existingTabs.tabs, { fields: [metaField], label: 'SEO' }],
tabs: [...existingTabs.tabs, { fields: [withoutHeading(metaField)], label: SEO_TAB }],
}
return {
...collection,
@@ -51,18 +57,20 @@ export function injectSeoTabs(config: Config, seo: SeoOption): Config {
}
}
// Otherwise wrap everything: Content tab + SEO tab.
// Otherwise wrap everything: Content tab + SEO tab. Sidebar fields (address,
// noindex…) stay outside the tabs, so they still show in the sidebar.
const inSidebar = (f: Field) => (f as { admin?: { position?: string } }).admin?.position === 'sidebar'
const tabs: TabsField = {
type: 'tabs',
tabs: [
{ fields: otherFields, label: collection.labels?.singular || 'Content' },
{ fields: [metaField], label: 'SEO' },
{ fields: otherFields.filter((f) => !inSidebar(f)), label: CONTENT_TAB },
{ fields: [withoutHeading(metaField)], label: SEO_TAB },
],
}
return {
...collection,
fields: [tabs],
fields: [tabs, ...otherFields.filter(inSidebar)],
}
}),
}
+77 -41
View File
@@ -1,9 +1,10 @@
import type { Field } from 'payload'
import type { AdminText } from '../admin-i18n/index.js'
import type { AiBotRule, AiBotsPolicy, RobotsOptions } from './buildRobots.js'
/**
* Site Settings → Search & AI: what editors set for search engines and AI
* Site settings → Search engines: what editors set for search engines and AI
* assistants without a deploy — Search Console / Bing verification codes, the
* AI crawler policy for robots.txt, and a note for llms.txt. Empty fields
* change nothing: verification tags appear only once a code is pasted, and the
@@ -36,87 +37,122 @@ export function normalizeVerificationToken(raw: unknown): string {
return /^[\w\-.:+/=]{1,200}$/.test(value) ? value : ''
}
const tokenField = (name: string, label: string, description: string): Field => ({
const tokenField = (name: string, product: string, description: AdminText): Field => ({
name,
type: 'text',
admin: { description },
hooks: { beforeChange: [({ value }) => normalizeVerificationToken(value) || null] },
label,
// A product name reads the same in every language.
label: { en: product, pl: product },
})
const AI_POLICY_OPTIONS = [
{ label: 'As set by the developer (default)', value: 'default' },
{ label: 'Allow all AI assistants and AI training', value: 'allow' },
{ label: 'Allow AI assistants and AI search, block AI training', value: 'block-training' },
{ label: 'Block all known AI bots', value: 'disallow' },
] as const
const AI_POLICY_OPTIONS: { label: AdminText; value: string }[] = [
{ label: { en: 'Default setting', pl: 'Ustawienie domyślne' }, value: 'default' },
{ label: { en: 'Allow all, including AI training', pl: 'Zezwól na wszystko, także trening AI' }, value: 'allow' },
{ label: { en: 'Allow assistants, block training', pl: 'Zezwól asystentom, blokuj trening' }, value: 'block-training' },
{ label: { en: 'Block all AI services', pl: 'Blokuj wszystkie usługi AI' }, value: 'disallow' },
]
/** The "Search & AI" tab fields. Not localized, except the llms.txt note. */
/**
* The "Search engines" tab fields. Not localized, except the llms.txt note.
* Order (admin-ux §7): the note (content) first, then verification codes and
* the AI access policy with its per-bot rules.
*/
export const searchSettingsFields: Field[] = [
{
name: LLMS_INTRO_FIELD,
type: 'textarea',
admin: {
description: {
en: 'Key facts AI assistants may quote: what you do, where, for whom and since when.',
pl: 'Najważniejsze fakty, które asystenci AI mogą cytować: czym zajmuje się firma, gdzie, dla kogo i od kiedy.',
},
},
label: { en: 'Site summary (llms.txt)', pl: 'Opis witryny (llms.txt)' },
localized: true,
},
{
name: SEARCH_VERIFICATION_FIELD,
type: 'group',
admin: {
description:
'Proves to search engines that you own this site. Paste the code (or the whole <meta> tag) from the search engine; it is added to every page. Leave empty if you verify another way (DNS, file).',
description: {
en: 'Paste the code or the whole meta tag from each tool; leave empty if you verify by DNS.',
pl: 'Wklej kod lub cały znacznik meta z narzędzia; zostaw puste przy weryfikacji przez DNS.',
},
},
fields: [
tokenField('google', 'Google Search Console', 'Search Console → Settings → Ownership verification → HTML tag.'),
tokenField('bing', 'Bing Webmaster Tools', 'Bing Webmaster Tools → Add site → HTML Meta Tag (msvalidate.01). Bing also powers ChatGPT Search and Copilot.'),
tokenField('yandex', 'Yandex Webmaster', 'Yandex Webmaster → Site verification → Meta tag.'),
tokenField('google', 'Google Search Console', {
en: 'Find it under Settings, Ownership verification, HTML tag.',
pl: 'Kod znajduje się w: Ustawienia, Weryfikacja własności, Tag HTML.',
}),
tokenField('bing', 'Bing Webmaster Tools', {
en: 'Find it under Add site, HTML Meta Tag; Bing also feeds ChatGPT Search and Copilot.',
pl: 'Kod znajduje się w: Dodaj witrynę, Tag meta HTML; z Bing korzystają też ChatGPT Search i Copilot.',
}),
tokenField('yandex', 'Yandex Webmaster', {
en: 'Find it under Site verification, Meta tag.',
pl: 'Kod znajduje się w: Weryfikacja witryny, Tag meta.',
}),
],
label: 'Search engine verification',
label: { en: 'Site verification', pl: 'Weryfikacja witryny' },
},
{
name: AI_CRAWLERS_FIELD,
type: 'group',
admin: {
description:
'Which AI bots may read the site (robots.txt). Assistants (ClaudeBot, ChatGPT-User, PerplexityBot…) fetch pages to answer questions and cite you; training crawlers (GPTBot, Google-Extended, CCBot…) collect pages to train models. Blocking assistants removes the site from AI answers.',
description: {
en: 'Which AI services may read the site; blocking assistants removes it from AI answers.',
pl: 'Które usługi AI mogą czytać witrynę; zablokowanie asystentów usuwa ją z odpowiedzi AI.',
},
},
fields: [
{
name: 'policy',
type: 'select',
defaultValue: 'default',
label: 'AI bots',
label: { en: 'Access', pl: 'Dostęp' },
options: AI_POLICY_OPTIONS.map((o) => ({ ...o })),
},
{
name: 'rules',
type: 'array',
admin: {
description:
'Exceptions for single bots, by user agent exactly as the bot announces itself (e.g. GPTBot, Bytespider). Wins over the setting above.',
description: {
en: 'Exceptions for single bots by name, e.g. GPTBot; they override the setting above.',
pl: 'Wyjątki dla pojedynczych botów według nazwy, np. GPTBot; mają pierwszeństwo przed ustawieniem powyżej.',
},
initCollapsed: true,
},
fields: [
{ name: 'userAgent', type: 'text', label: 'User agent', required: true },
{
name: 'access',
type: 'select',
defaultValue: 'disallow',
options: [
{ label: 'Allow', value: 'allow' },
{ label: 'Block', value: 'disallow' },
type: 'row',
fields: [
{
name: 'userAgent',
type: 'text',
admin: { placeholder: 'GPTBot' },
label: { en: 'Bot name', pl: 'Nazwa bota' },
required: true,
},
{
name: 'access',
type: 'select',
defaultValue: 'disallow',
label: { en: 'Access', pl: 'Dostęp' },
options: [
{ label: { en: 'Allow', pl: 'Zezwól' }, value: 'allow' },
{ label: { en: 'Block', pl: 'Blokuj' }, value: 'disallow' },
],
required: true,
},
],
required: true,
},
],
label: 'Per-bot exceptions',
label: { en: 'Bot rules', pl: 'Reguły dla botów' },
labels: { plural: { en: 'Rules', pl: 'Reguły' }, singular: { en: 'Rule', pl: 'Reguła' } },
},
],
label: 'AI crawlers',
},
{
name: LLMS_INTRO_FIELD,
type: 'textarea',
admin: {
description:
'Shown at the top of /llms.txt, under the site description: key facts an AI assistant should know and may quote — what you do, where, for whom, since when. Plain sentences, no marketing slogans.',
},
label: 'About the site for AI assistants (llms.txt)',
localized: true,
label: { en: 'AI assistants', pl: 'Asystenci AI' },
},
]
+35 -3
View File
@@ -2,6 +2,7 @@ import type { Field, Plugin } from 'payload'
import { seoPlugin } from '@payloadcms/plugin-seo'
import type { AdminText } from '../admin-i18n/define.js'
import type { SeoOption } from './types.js'
type BuildSeoPluginArgs = {
@@ -19,12 +20,43 @@ const titleOverrideField: Field = {
name: 'titleOverride',
type: 'text',
admin: {
description:
'Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.',
description: {
en: 'Replaces the whole title, site name included; leave empty to build it automatically.',
pl: 'Zastępuje cały tytuł razem z nazwą witryny; zostaw puste, aby utworzyć go automatycznie.',
},
},
label: { en: 'Exact page title', pl: 'Dokładny tytuł strony' },
localized: true,
}
/** Panel wording for plugin-seo's own fields (labels only; names and data unchanged). */
const SEO_FIELD_TEXTS: Record<string, { description?: AdminText; label: AdminText }> = {
description: { label: { en: 'Description', pl: 'Opis' } },
image: {
description: {
en: 'Shown when the page is shared; best under 500 KB.',
pl: 'Widoczny przy udostępnianiu strony; najlepiej poniżej 500 KB.',
},
label: { en: 'Share image', pl: 'Obraz udostępniania' },
},
overview: { label: { en: 'Overview', pl: 'Przegląd' } },
preview: { label: { en: 'Preview', pl: 'Podgląd' } },
title: { label: { en: 'Page title', pl: 'Tytuł strony' } },
}
function withSeoLabels(fields: Field[]): Field[] {
return fields.map((field) => {
const texts = 'name' in field ? SEO_FIELD_TEXTS[field.name] : undefined
if (!texts) {return field}
const admin = (field as { admin?: Record<string, unknown> }).admin
return {
...field,
...(texts.description ? { admin: { ...admin, description: texts.description } } : {}),
label: texts.label,
} as Field
})
}
/**
* Admin hint right under meta.description (MetaDescriptionCheck): empty,
* same as the site-wide description, or same as another document's.
@@ -71,7 +103,7 @@ export function buildSeoPlugin({ seo, uploadsCollection = seo.uploadsCollection
return seoPlugin({
collections: seo.collections,
fields: ({ defaultFields }) => [
...afterDescription(defaultFields, descriptionCheckField(seo)),
...afterDescription(withSeoLabels(defaultFields), descriptionCheckField(seo)),
titleOverrideField,
...(seo.fields ?? []),
],
+10 -3
View File
@@ -64,19 +64,26 @@ export function buildSlugField(options: BuildSlugFieldOptions = {}): Field {
return value
}
const { admin: adminOverrides, ...restOverrides } = overrides
return {
name,
type: 'text',
admin: {
description: 'Auto-generated from the title when left empty. You can override it.',
...overrides.admin,
description: {
en: 'Leave empty to create it from the title.',
pl: 'Zostaw puste, aby utworzyć go z tytułu.',
},
position: 'sidebar',
...adminOverrides,
},
hooks: {
beforeValidate: [autoGenerate],
},
index: true,
label: { en: 'Address (URL)', pl: 'Adres (URL)' },
localized,
required,
...overrides,
...restOverrides,
} as TextField
}
+23 -3
View File
@@ -1,8 +1,28 @@
/** Nav link to /admin/stats (admin.components.afterNavLinks). */
export function StatsNavLink({ adminRoute = '/admin' }: { adminRoute?: string }) {
import type { Payload } from 'payload'
import type { StatsI18n } from './statsI18n.js'
import { canReadStats } from './canReadStats.js'
import { statsI18n, tr } from './statsI18n.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
i18n?: StatsI18n
payload?: Payload
user?: unknown
}
/**
* Nav link to /admin/stats (admin.components.afterNavLinks), shown right after
* the Statistics group, so it reads "Overview". Hidden for users the
* stats-visits collection does not let read.
*/
export async function StatsNavLink({ adminRoute = '/admin', i18n, payload, user }: Props) {
if (!payload || !(await canReadStats(payload, undefined, user))) {return null}
return (
<a className="nav__link" href={`${adminRoute.replace(/\/$/, '')}/stats`} id="nav-ipal-stats">
<span className="nav__link-label">Statistics</span>
<span className="nav__link-label">{tr(statsI18n(i18n), 'statsNavLink')}</span>
</a>
)
}
+52 -40
View File
@@ -5,18 +5,19 @@ import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { formatDateTime } from '../../admin-i18n/t.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { canReadStats } from './canReadStats.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { deviceLabel, num, plural, type StatsI18n, tr } from './statsI18n.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))
const timeOnly = (iso: string, language: string, timeZone: string) =>
new Intl.DateTimeFormat(language, { timeStyle: 'short', timeZone }).format(new Date(iso))
function TopList({ rows, title, unit }: { rows: [string, number][]; title: string; unit: string }) {
function TopList({ i18n, label, rows, title, unit }: { i18n: StatsI18n; label?: (key: string) => React.ReactNode; rows: [string, number][]; title: string; unit: string }) {
return (
<section>
<h3>{title}</h3>
@@ -31,39 +32,39 @@ function TopList({ rows, title, unit }: { rows: [string, number][]; title: strin
<tbody>
{rows.map(([key, count]) => (
<tr key={key}>
<td><code>{key}</code></td>
<td>{fmt(count)}</td>
<td>{label ? label(key) : <code>{key}</code>}</td>
<td>{num(i18n, count)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No data yet.</p>
<p>{tr(i18n, 'statsNoData')}</p>
)}
</section>
)
}
function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
function VisitorHistory({ base, i18n, timeZone, visitorId, visits }: { base: string; i18n: StatsI18n; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
const lang = i18n.language
return (
<>
<p><a href={base}>← All statistics</a></p>
<h1>Visitor <code>{visitorId}</code></h1>
<p><a href={base}>{tr(i18n, 'statsBack')}</a></p>
<h1>{tr(i18n, 'statsVisitorHeading')} <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.
{plural(i18n, 'statsVisitorVisits', visits.length)} {tr(i18n, 'statsVisitorErase')}
</p>
{visits.map((v) => (
<section className="ipal-stats-tile" key={v.id} style={{ marginBottom: '1rem' }}>
<strong>{when(v.startedAt, timeZone)}</strong>
<strong>{formatDateTime(v.startedAt, lang, timeZone)}</strong>
<span>
{' '}· {v.pageCount} page{v.pageCount === 1 ? '' : 's'} · {v.device ?? 'unknown device'}
{v.referrer ? ` · from ${v.referrer}` : ''}
{' '}· {plural(i18n, 'statsPages', v.pageCount)} · {deviceLabel(i18n, v.device)}
{v.referrer ? ` · ${tr(i18n, 'statsFrom', { referrer: 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>
<code>{p.p}</code> <span>{timeOnly(p.t, lang, timeZone)}</span>
</li>
))}
</ol>
@@ -87,60 +88,71 @@ export async function StatsView(props: Props) {
const visitorParam = typeof searchParams?.visitor === 'string' ? searchParams.visitor : undefined
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
const i18n = req.i18n as unknown as StatsI18n
const lang = i18n.language
let content: React.ReactNode
if (!(await canReadStats(req.payload, req))) {
content = <p>You do not have access to the statistics.</p>
content = <p>{tr(i18n, 'statsNoAccess')}</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
content = <VisitorHistory base={base} i18n={i18n} 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)
const visits = tr(i18n, 'statsVisits')
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>
<h1>{tr(i18n, 'statsTitle')}</h1>
<p>{tr(i18n, 'statsIntro')}</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>{num(i18n, totals.visits)}</b><span>{visits}</span></div>
<div className="ipal-stats-tile"><b>{num(i18n, totals.views)}</b><span>{tr(i18n, 'statsPageViews')}</span></div>
<div className="ipal-stats-tile">
<b>{totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}</b><span>Pages per visit</span>
<b>{num(i18n, totals.visits ? totals.views / totals.visits : 0, { maximumFractionDigits: 1, minimumFractionDigits: 1 })}</b>
<span>{tr(i18n, 'statsPagesPerVisit')}</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 className="ipal-stats-tile">
<b>{num(i18n, totals.bounceRate, { maximumFractionDigits: 0, style: 'percent' })}</b>
<span>{tr(i18n, 'statsSinglePageVisits')}</span>
</div>
<div className="ipal-stats-tile"><b>{num(i18n, totals.consented)}</b><span>{tr(i18n, 'statsConsentedVisits')}</span></div>
</div>
<h2>Visits per day</h2>
<VisitsChart days={stats.days} />
<h2>{tr(i18n, 'statsVisitsPerDay')}</h2>
<VisitsChart days={stats.days} i18n={i18n} />
<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" />
<TopList i18n={i18n} rows={stats.topPages} title={tr(i18n, 'statsColPage')} unit={tr(i18n, 'statsColViews')} />
<TopList i18n={i18n} rows={stats.entries} title={tr(i18n, 'statsColEntryPage')} unit={visits} />
<TopList
i18n={i18n}
label={(key) => (key === '(direct)' ? tr(i18n, 'statsDirect') : <code>{key}</code>)}
rows={stats.referrers}
title={tr(i18n, 'statsColReferrer')}
unit={visits}
/>
<TopList i18n={i18n} label={(key) => deviceLabel(i18n, key)} rows={stats.devices} title={tr(i18n, 'statsColDevice')} unit={visits} />
</div>
<section style={{ marginTop: '2rem' }}>
<h3>Visitor history (analytics consent only)</h3>
<h3>{tr(i18n, 'statsVisitorHistory')}</h3>
{visitors.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Visitor</th>
<th scope="col">Last seen</th>
<th scope="col">{tr(i18n, 'statsColVisitor')}</th>
<th scope="col">{tr(i18n, 'statsColLastVisit')}</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>
<td><a aria-label={tr(i18n, 'statsVisitorLink', { id: v.visitorId })} href={`${base}?visitor=${v.visitorId}`}><code>{v.visitorId}</code></a></td>
<td>{formatDateTime(v.lastAt, lang, timeZone)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No visitor has accepted analytics cookies yet.</p>
<p>{tr(i18n, 'statsNoVisitors')}</p>
)}
</section>
</>
+10 -5
View File
@@ -1,12 +1,16 @@
import type { Payload, PayloadRequest } from 'payload'
import type { StatsI18n } from './statsI18n.js'
import { canReadStats } from './canReadStats.js'
import { loadStats } from './loadStats.js'
import { num, statsI18n, tr } from './statsI18n.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
i18n?: StatsI18n
payload?: Payload
req?: PayloadRequest
timeZone?: string
@@ -19,8 +23,9 @@ type Props = {
* collection lets read (admins by default); renders nothing on
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
export async function StatsWidget({ adminRoute = '/admin', i18n: i18nProp, payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !(await canReadStats(payload, req, user))) {return null}
const i18n = statsI18n(i18nProp ?? (req?.i18n as StatsI18n | undefined))
let stats
try {
stats = await loadStats(payload, { timeZone })
@@ -30,12 +35,12 @@ export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZon
return (
<section className="ipal-stats" style={{ marginBottom: '2rem' }}>
<style>{STATS_CSS}</style>
<h2 style={{ marginBottom: '0.25rem' }}>Visits per day</h2>
<h2 style={{ marginBottom: '0.25rem' }}>{tr(i18n, 'statsVisitsPerDay')}</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>
{tr(i18n, 'statsWidgetSummary', { views: num(i18n, stats.totals.views), visits: num(i18n, stats.totals.visits) })} ·{' '}
<a href={`${adminRoute.replace(/\/$/, '')}/stats`}>{tr(i18n, 'statsWidgetLink')}</a>
</p>
<VisitsChart days={stats.days} />
<VisitsChart days={stats.days} i18n={i18n} />
</section>
)
}
+22 -12
View File
@@ -1,4 +1,7 @@
import type { StatsDay } from '../summarize.js'
import type { StatsI18n } from './statsI18n.js'
import { num, statsI18n, tr } from './statsI18n.js'
const W = 1000
const H = 220
@@ -18,14 +21,21 @@ function column(x: number, y: number, w: number, h: number): string {
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)}`
/** A `YYYY-MM-DD` day in the admin language: short (axis) or medium (table, tooltip). */
const dayLabel = (day: string, language: string, style: 'medium' | 'short') =>
new Intl.DateTimeFormat(
language,
style === 'short' ? { day: 'numeric', month: 'numeric', timeZone: 'UTC' } : { dateStyle: 'medium', timeZone: 'UTC' },
).format(new Date(`${day}T00:00:00Z`))
/**
* 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[] }) {
export function VisitsChart({ days, i18n: i18nProp }: { days: StatsDay[]; i18n?: StatsI18n }) {
const i18n = statsI18n(i18nProp)
const lang = i18n.language
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
@@ -41,7 +51,7 @@ export function VisitsChart({ days }: { days: StatsDay[] }) {
<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)}
{num(i18n, t, { maximumFractionDigits: 1 })}
</text>
</g>
))}
@@ -51,12 +61,12 @@ export function VisitsChart({ days }: { days: StatsDay[] }) {
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>
<title>{tr(i18n, 'statsChartDay', { day: dayLabel(d.day, lang, 'medium'), views: num(i18n, d.views), visits: num(i18n, d.visits) })}</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)}
{dayLabel(d.day, lang, 'short')}
</text>
) : null}
</g>
@@ -64,21 +74,21 @@ export function VisitsChart({ days }: { days: StatsDay[] }) {
})}
</svg>
<details style={{ marginTop: '0.5rem' }}>
<summary>Table</summary>
<summary>{tr(i18n, 'statsChartTable')}</summary>
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Day</th>
<th scope="col">Visits</th>
<th scope="col">Page views</th>
<th scope="col">{tr(i18n, 'statsColDay')}</th>
<th scope="col">{tr(i18n, 'statsVisits')}</th>
<th scope="col">{tr(i18n, 'statsPageViews')}</th>
</tr>
</thead>
<tbody>
{[...days].reverse().map((d) => (
<tr key={d.day}>
<td>{d.day}</td>
<td>{d.visits}</td>
<td>{d.views}</td>
<td>{dayLabel(d.day, lang, 'medium')}</td>
<td>{num(i18n, d.visits)}</td>
<td>{num(i18n, d.views)}</td>
</tr>
))}
</tbody>
+40
View File
@@ -0,0 +1,40 @@
import type { AdminTextKey } from '../../admin-i18n/texts/index.js'
import { formatNumber, ipalT } from '../../admin-i18n/t.js'
import { adminTexts } from '../../admin-i18n/texts/index.js'
/** The part of Payload's server `i18n` the stats components use. */
export type StatsI18n = { language: string; t: (key: never, vars?: Record<string, unknown>) => string }
/** Payload passes `i18n` to admin server components; without it, English. */
const englishOnly: StatsI18n = {
language: 'en',
t: ((key: string, vars?: Record<string, unknown>) => {
const text = (adminTexts.en as Record<string, string>)[key.replace(/^ipal:/, '')] ?? key
return text.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String((vars?.[name] as number | string | undefined) ?? ''))
}) as StatsI18n['t'],
}
export const statsI18n = (i18n?: null | StatsI18n): StatsI18n => i18n ?? englishOnly
export const tr = (i18n: StatsI18n, key: AdminTextKey, vars?: Record<string, unknown>) => ipalT(i18n.t, key, vars)
/** Number in the admin language, e.g. 1 234 (pl) / 1,234 (en). */
export const num = (i18n: StatsI18n, n: number, options?: Intl.NumberFormatOptions) =>
options ? new Intl.NumberFormat(i18n.language, options).format(n) : formatNumber(n, i18n.language)
const PLURAL_SUFFIX = { few: 'Few', many: 'Many', one: 'One', other: 'Other', two: 'Other', zero: 'Other' } as const
/** Plural text: `base` + One / Few / Many / Other, picked by Intl.PluralRules for the admin language. */
export function plural(i18n: StatsI18n, base: 'statsPages' | 'statsVisitorVisits', count: number): string {
const category = new Intl.PluralRules(i18n.language).select(count)
return tr(i18n, `${base}${PLURAL_SUFFIX[category]}` as AdminTextKey, { count: num(i18n, count) })
}
/** Panel name of a stored device value. */
export function deviceLabel(i18n: StatsI18n, device: null | string | undefined): string {
if (device === 'desktop') {return tr(i18n, 'statsDeviceDesktop')}
if (device === 'mobile') {return tr(i18n, 'statsDeviceMobile')}
if (device === 'tablet') {return tr(i18n, 'statsDeviceTablet')}
return device || tr(i18n, 'statsUnknownDevice')
}
+42 -16
View File
@@ -63,37 +63,63 @@ export function buildStatsCollection(): CollectionConfig {
},
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',
description: {
en: 'Visits counted by the built-in statistics, without IP addresses.',
pl: 'Wizyty liczone przez wbudowane statystyki, bez adresów IP.',
},
group: { en: 'Statistics', pl: 'Statystyki' },
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: 'day', type: 'text', index: true, label: { en: 'Day', pl: 'Dzień' }, required: true },
{
name: 'startedAt',
type: 'date',
admin: { date: { pickerAppearance: 'dayAndTime' } },
label: { en: 'Start', pl: 'Początek' },
required: true,
},
{
name: 'lastAt',
type: 'date',
admin: { date: { pickerAppearance: 'dayAndTime' } },
index: true,
label: { en: 'Last activity', pl: 'Ostatnia aktywność' },
required: true,
},
{ name: 'entry', type: 'text', label: { en: 'Entry page', pl: 'Strona wejścia' }, required: true },
{ name: 'exit', type: 'text', label: { en: 'Exit page', pl: 'Strona wyjścia' }, required: true },
{ name: 'pageCount', type: 'number', label: { en: 'Pages viewed', pl: 'Liczba stron' }, required: true },
{ name: 'pages', type: 'json', label: { en: 'Pages', pl: 'Strony' } },
{ name: 'referrer', type: 'text', label: { en: 'Referrer', pl: 'Strona odsyłająca' } },
{
name: 'device',
type: 'select',
options: ['desktop', 'mobile', 'tablet'],
label: { en: 'Device', pl: 'Urządzenie' },
options: [
{ label: { en: 'Desktop', pl: 'Komputer' }, value: 'desktop' },
{ label: { en: 'Mobile', pl: 'Telefon' }, value: 'mobile' },
{ label: { en: 'Tablet', pl: 'Tablet' }, value: 'tablet' },
],
},
{ name: 'locale', type: 'text' },
{ name: 'country', type: 'text' },
{ name: 'locale', type: 'text', label: { en: 'Language', pl: 'Język' } },
{ name: 'country', type: 'text', label: { en: 'Country', pl: 'Kraj' } },
{
name: 'visitorId',
type: 'text',
admin: { description: 'Only with analytics consent — the id from the visitor’s ipal_vid cookie.' },
admin: {
description: {
en: 'Set only for visitors who accepted analytics cookies.',
pl: 'Tylko u odwiedzających, którzy zaakceptowali cookies analityczne.',
},
},
index: true,
label: { en: 'Visitor ID', pl: 'Identyfikator odwiedzającego' },
},
// 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' },
labels: { plural: { en: 'Visits', pl: 'Wizyty' }, singular: { en: 'Visit', pl: 'Wizyta' } },
timestamps: false,
}
}
+11 -2
View File
@@ -208,11 +208,20 @@ function withReadOnlyMedia(
beforeOperation: [
...(collection.hooks?.beforeOperation ?? []),
({ args, operation }) => {
const req = (args as { req?: { file?: unknown } }).req
const req = (args as {
req?: { file?: unknown; i18n?: { language?: string }; payload?: { logger?: { warn: (msg: string) => void } } }
}).req
if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) {
req?.payload?.logger?.warn(
'[ipal] R2 storage: media is read-only (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
)
throw new APIError(
'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
req?.i18n?.language === 'pl'
? 'W tej kopii witryny nie można przesyłać ani usuwać plików. Zapytaj administratora.'
: 'Files cannot be uploaded or deleted in this copy of the site. Ask your administrator.',
403,
undefined,
true,
)
}
return args
+14 -7
View File
@@ -28,15 +28,22 @@ function resolveKeys(integrations: IntegrationsWithTurnstileKeys) {
}
/**
* Why Turnstile is half-configured (only one of the two keys set), or null when
* it's fully on or fully off. Shown as a dashboard alert by IntegrationAlerts —
* the half-configured state silently turns Turnstile OFF, which an editor who
* just pasted one key wouldn't expect.
* Which key is missing when Turnstile is half-configured (only one of the two
* keys set), or null when it's fully on or fully off. The half-configured state
* silently turns Turnstile OFF, which an editor who just pasted one key wouldn't
* expect — IntegrationAlerts shows it on the dashboard.
*/
export function turnstileKeyProblem(integrations: IntegrationsWithTurnstileKeys): null | string {
export function turnstileMissingKey(integrations: IntegrationsWithTurnstileKeys): 'secret' | 'site' | null {
const { secret, siteKey } = resolveKeys(integrations)
if (Boolean(siteKey) === Boolean(secret)) {return null}
return `${siteKey ? 'Secret key' : 'Site key'} is missing, so Turnstile is OFF — forms are not protected. Fill in both keys (or clear both).`
return siteKey ? 'secret' : 'site'
}
/** Plain English explanation of a half-configured Turnstile, or null (see turnstileMissingKey). */
export function turnstileKeyProblem(integrations: IntegrationsWithTurnstileKeys): null | string {
const missing = turnstileMissingKey(integrations)
if (!missing) {return null}
return `The ${missing === 'secret' ? 'secret' : 'site'} key is missing, so spam protection is off. Fill in both keys or clear both.`
}
/**
@@ -68,7 +75,7 @@ export async function getTurnstileConfig(payload: BasePayload): Promise<Turnstil
warnedPartial = true
console.warn(
`[ipal] Turnstile is half-configured (${siteKey ? 'secret key' : 'site key'} missing) — ` +
'treating it as off. Fill in both keys in Site Integrations → Turnstile.',
'treating it as off. Fill in both keys in Site integrations → Spam protection.',
)
}
return { enabled: false, siteKey: null }
+17 -9
View File
@@ -59,17 +59,25 @@ const STATUS_FIELD = 'turnstileStatus'
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */
/**
* Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor.
* The messages are what the panel shows (in English; the banner and dashboard alert
* show these codes in the editor's language — integrations/texts.ts STATUS_CODE_TEXTS).
*/
const CONFIG_ERRORS: Record<string, string> = {
'internal-error': 'Cloudflare reported an internal error while verifying.',
'invalid-input-secret':
'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
'missing-input-secret': 'The secret key is missing in the request.',
'internal-error': 'Cloudflare reported an internal error. It usually passes on its own.',
'invalid-input-secret': 'Cloudflare rejected the secret key. Both keys must come from the same widget.',
'missing-input-secret': 'The secret key is missing.',
}
const PLUGIN_ERRORS: Record<string, string> = {
'bad-response': 'Cloudflare returned an unexpected response.',
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
'bad-response': 'Cloudflare sent an unexpected response.',
'missing-secret': 'The secret key is missing.',
'network-error': 'The server could not reach Cloudflare.',
}
/** Developer detail for the server log only. */
const LOG_DETAIL: Record<string, string> = {
'missing-secret': `set it in Site integrations → Spam protection or the ${ENV_SECRET} environment variable`,
'network-error': 'challenges.cloudflare.com unreachable',
}
/**
@@ -94,7 +102,7 @@ export async function checkTurnstile({
const degraded = async (code: string): Promise<TurnstileCheck> => {
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)
console.warn(`[ipal] Turnstile degraded (${code}): ${message}${LOG_DETAIL[code] ? ` (${LOG_DETAIL[code]})` : ''}`)
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
return { code, outcome: 'degraded' }
}