From 6b46bc0c144c89b703d9fa6c0f8a35bf7a703b61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 27 Oct 2026 15:46:25 +0100 Subject: [PATCH] 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 --- src/exports/client.ts | 9 +- src/exports/rsc.ts | 2 +- src/globals/CookieSettings/fields.ts | 355 +++++++++++------- src/globals/CookieSettings/index.ts | 4 +- src/globals/Notifications/fields.ts | 153 ++++---- src/globals/Notifications/index.ts | 6 +- .../components/MaskedField.tsx | 13 +- .../components/TestEmailButton.tsx | 34 +- .../SiteIntegrations/fields/analytics.ts | 52 +-- src/globals/SiteIntegrations/fields/smtp.ts | 89 +++-- .../SiteIntegrations/fields/turnstile.ts | 20 +- src/globals/SiteIntegrations/index.ts | 21 +- src/globals/SiteSettings/fields/general.ts | 133 ++++--- src/globals/SiteSettings/fields/theme.ts | 24 +- src/globals/SiteSettings/index.ts | 30 +- src/index.ts | 19 +- src/modules/access/rolesField.ts | 18 +- .../accessibility/AccessibilityWidget.tsx | 80 ++-- src/modules/accessibility/client.ts | 2 +- src/modules/accessibility/index.ts | 2 +- src/modules/admin-i18n/apply.ts | 32 ++ src/modules/admin-i18n/define.ts | 14 + src/modules/admin-i18n/index.ts | 6 + src/modules/admin-i18n/t.ts | 19 + src/modules/admin-i18n/texts/consent.ts | 7 + src/modules/admin-i18n/texts/content.ts | 112 ++++++ src/modules/admin-i18n/texts/index.ts | 12 + src/modules/admin-i18n/texts/integrations.ts | 104 +++++ src/modules/admin-i18n/texts/settings.ts | 11 + src/modules/admin-ui/RowLabelComponent.tsx | 24 +- src/modules/admin-ui/rowLabel.ts | 5 +- src/modules/analytics/idFormats.ts | 10 +- src/modules/blocks/sectionFields.ts | 45 ++- src/modules/branding/adminGraphics.tsx | 15 +- src/modules/consent/CookieTable.tsx | 20 +- src/modules/consent/categoryLabels.ts | 15 + src/modules/consent/consentLog.ts | 20 +- src/modules/consent/getConsentTexts.ts | 49 ++- src/modules/consent/index.ts | 3 +- .../consent/scanner/CookieScanButton.tsx | 5 +- src/modules/consent/scanner/collection.ts | 2 +- .../consent/scanner/crawl/endpoints.ts | 4 +- src/modules/consent/scanner/crawl/global.ts | 14 +- src/modules/consent/scanner/crawl/ingest.ts | 2 +- src/modules/consent/scanner/labels.ts | 164 ++++---- .../construction/ConstructionNotice.tsx | 2 +- src/modules/construction/fields.ts | 50 ++- src/modules/content/archiveFields.ts | 22 +- src/modules/content/types.ts | 4 +- src/modules/email/graphAdapter.ts | 12 +- src/modules/email/mailAdapter.ts | 3 +- src/modules/email/panelSmtpAdapter.ts | 6 +- src/modules/email/sendEmail.ts | 6 +- src/modules/email/test/testEmailEndpoint.ts | 53 ++- src/modules/forms/builderBlocks.ts | 111 ++++-- src/modules/forms/emailLayout.ts | 36 +- src/modules/forms/formAnalyticsFields.ts | 26 +- src/modules/forms/formsPluginConfig.ts | 146 ++++++- src/modules/forms/index.ts | 5 +- src/modules/forms/submitForm.ts | 24 ++ src/modules/forms/types.ts | 2 +- src/modules/forms/useBuilderForm.ts | 8 +- src/modules/forms/useForm.ts | 12 +- src/modules/forms/validators.ts | 76 +++- src/modules/hooks/preventDeleteSystemPage.ts | 11 +- src/modules/hooks/validateUniqueRole.ts | 64 +++- .../integrations/IntegrationAlerts.tsx | 45 ++- .../integrations/IntegrationStatusBanner.tsx | 60 +-- src/modules/integrations/index.ts | 3 +- src/modules/integrations/status.ts | 26 +- src/modules/integrations/texts.ts | 41 ++ src/modules/lightbox/index.ts | 2 +- src/modules/lightbox/texts.ts | 25 +- src/modules/links/buildLinkField.ts | 55 ++- src/modules/media/optimizeUpload.ts | 41 +- src/modules/notifications/defaults.ts | 33 +- .../notifications/getNotificationTexts.ts | 12 +- src/modules/notifications/index.ts | 2 +- .../notifications/resolveFormMessage.ts | 9 +- src/modules/pages/systemPagesFields.ts | 47 ++- src/modules/richtext/headings.ts | 24 +- src/modules/seo/MetaDescriptionCheck.tsx | 21 +- src/modules/seo/buildNoindexField.ts | 26 +- src/modules/seo/buildSummaryField.ts | 17 +- src/modules/seo/indexNow.ts | 7 +- src/modules/seo/injectSeoTabs.ts | 18 +- src/modules/seo/searchSettings.ts | 118 ++++-- src/modules/seo/seoPluginConfig.ts | 38 +- src/modules/slug/buildSlugField.ts | 13 +- src/modules/stats/admin/StatsNavLink.tsx | 26 +- src/modules/stats/admin/StatsView.tsx | 92 +++-- src/modules/stats/admin/StatsWidget.tsx | 15 +- src/modules/stats/admin/VisitsChart.tsx | 34 +- src/modules/stats/admin/statsI18n.ts | 40 ++ src/modules/stats/collection.ts | 58 ++- src/modules/storage/buildR2Storage.ts | 13 +- src/modules/turnstile/config.ts | 21 +- src/modules/turnstile/verify.ts | 26 +- src/plugin.ts | 4 + test/adminUx.test.ts | 237 ++++++++++++ test/drafts.test.ts | 2 +- test/integration.test.ts | 12 +- test/lightbox.test.ts | 3 + test/links.test.ts | 6 +- test/plugin.test.ts | 12 +- test/seoSearch.test.ts | 14 +- test/storage.test.ts | 4 +- test/submitForm.test.ts | 26 +- 108 files changed, 2806 insertions(+), 981 deletions(-) create mode 100644 src/modules/admin-i18n/apply.ts create mode 100644 src/modules/admin-i18n/define.ts create mode 100644 src/modules/admin-i18n/index.ts create mode 100644 src/modules/admin-i18n/t.ts create mode 100644 src/modules/admin-i18n/texts/consent.ts create mode 100644 src/modules/admin-i18n/texts/content.ts create mode 100644 src/modules/admin-i18n/texts/index.ts create mode 100644 src/modules/admin-i18n/texts/integrations.ts create mode 100644 src/modules/admin-i18n/texts/settings.ts create mode 100644 src/modules/consent/categoryLabels.ts create mode 100644 src/modules/integrations/texts.ts create mode 100644 src/modules/stats/admin/statsI18n.ts create mode 100644 test/adminUx.test.ts diff --git a/src/exports/client.ts b/src/exports/client.ts index 59b99d0..2eac05d 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -1,5 +1,5 @@ 'use client' -export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js' +export { A11Y_DEFAULT_TEXTS, AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js' export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js' export { Analytics } from '../modules/analytics/client.js' export type { AnalyticsProps } from '../modules/analytics/client.js' @@ -53,12 +53,15 @@ export { custom, email, isEmail, + localizedRules, maxLength, minLength, pattern, required, + VALIDATION_MESSAGES, + validationMessages, } from '../modules/forms/validators.js' -export type { Rule } from '../modules/forms/validators.js' +export type { Rule, ValidationMessages } from '../modules/forms/validators.js' export { AlternateLinksProvider, AlternateLinksUpdater, @@ -78,7 +81,7 @@ export { export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js' export { LightboxDialog, LightboxProvider, LightboxTrigger, prefersReducedMotion, useLightbox, useOptionalLightbox } from '../modules/lightbox/client.js' export type { LightboxApi, LightboxDialogProps, LightboxProviderProps, LightboxTriggerProps } from '../modules/lightbox/client.js' -export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxImage, lightboxIndex, resolveLightboxTexts } from '../modules/lightbox/index.js' +export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from '../modules/lightbox/index.js' export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from '../modules/lightbox/index.js' export { LocaleView } from '../modules/pages/LocaleView.js' export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js' diff --git a/src/exports/rsc.ts b/src/exports/rsc.ts index e79528e..dc9d37e 100644 --- a/src/exports/rsc.ts +++ b/src/exports/rsc.ts @@ -12,7 +12,7 @@ export type { EnhanceProps, RenderBlocksProps, } from '../modules/blocks/index.js' -export { CookieTable } from '../modules/consent/CookieTable.js' +export { COOKIE_TABLE_LABELS, CookieTable } from '../modules/consent/CookieTable.js' export type { CookieTableLabels } from '../modules/consent/CookieTable.js' export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/RenderForm.js' export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js' diff --git a/src/globals/CookieSettings/fields.ts b/src/globals/CookieSettings/fields.ts index c53b265..d338c10 100644 --- a/src/globals/CookieSettings/fields.ts +++ b/src/globals/CookieSettings/fields.ts @@ -1,163 +1,254 @@ import type { Field } from 'payload' -import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js' +import { rowLabel } from '../../modules/admin-ui/index.js' +import { consentCategoryOptions } from '../../modules/consent/categoryLabels.js' + +const DEFAULT_HINT = { en: 'Leave empty to use the default.', pl: 'Zostaw puste, aby użyć domyślnej wartości.' } +const HIDDEN_HINT = { en: 'Leave empty to hide it.', pl: 'Zostaw puste, aby go nie pokazywać.' } /** * Fields for the CookieSettings global — GDPR consent banner copy, editable * per locale. The privacy-policy link TARGET is NOT stored here: it comes from * the pages module (system page role 'privacyPolicy'), keeping one source of * truth. Only the link's visible text lives here (privacyLinkLabel). + * + * The tabs are unnamed (presentation only): the data stays flat, as before. */ export const cookieSettingsFields: Field[] = [ { name: 'policyVersion', type: 'number', admin: { - description: - 'Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.', + description: { + en: 'Raise by 1 after adding a tool or changing the cookie policy, and every visitor is asked for consent again.', + pl: 'Zwiększ o 1 po dodaniu narzędzia lub zmianie polityki cookies, a każdy odwiedzający zostanie ponownie zapytany o zgodę.', + }, position: 'sidebar', step: 1, }, defaultValue: 1, + label: { en: 'Consent version', pl: 'Wersja zgody' }, min: 1, required: true, }, { - name: 'eyebrow', - type: 'text', - admin: { - description: 'Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.', - }, - localized: true, - }, - { - name: 'title', - type: 'text', - admin: { - description: 'Banner heading, e.g. "We respect your privacy". Empty → not shown.', - }, - localized: true, - }, - { - name: 'message', - type: 'textarea', - admin: { - description: 'Main consent message shown in the banner.', - }, - localized: true, - }, - { - name: 'settingsTitle', - type: 'text', - admin: { - description: 'Heading for the detailed settings panel.', - }, - localized: true, - }, - { - name: 'settingsDescription', - type: 'textarea', - admin: { - description: 'Intro under the settings heading — what cookies are for and that the choice can be changed later.', - }, - localized: true, - }, - { - name: 'alwaysActiveLabel', - type: 'text', - admin: { - description: 'Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.', - }, - localized: true, - }, - { - name: 'privacyLinkLabel', - type: 'text', - admin: { - description: - 'Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.', - }, - localized: true, - }, - { - name: 'buttons', - type: 'group', - admin: { - description: 'Button labels.', - }, - fields: [ - { name: 'acceptAll', type: 'text', localized: true }, - { name: 'reject', type: 'text', localized: true }, - { name: 'settings', type: 'text', localized: true }, - // Not `save`: Mongoose reserves that path name and warns on every start/build. - { name: 'savePreferences', type: 'text', label: 'Save', localized: true }, - { name: 'back', type: 'text', localized: true }, + type: 'tabs', + tabs: [ { - name: 'close', - type: 'text', - admin: { description: 'Screen-reader label of the ✕ button in the settings dialog.' }, - localized: true, - }, - ], - }, - { - name: 'detailLabels', - type: 'group', - admin: { - description: - 'Labels of the cookie list in the detailed settings window (CookieBanner settings="detailed"). The list itself comes from Cookies below.', - }, - fields: [ - { name: 'cookies', type: 'text', admin: { description: 'Expander under each category, e.g. "Cookies used" — the count is added.' }, localized: true }, - { name: 'provider', type: 'text', localized: true }, - { name: 'purpose', type: 'text', localized: true }, - { name: 'duration', type: 'text', localized: true }, - ], - }, - { - name: 'categories', - type: 'array', - admin: { - description: 'Per-category titles and descriptions.', - }, - fields: [ - { - name: 'key', - type: 'select', - options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })), - required: true, - }, - { name: 'title', type: 'text', localized: true }, - { name: 'description', type: 'textarea', localized: true }, - ], - }, - { - name: 'cookies', - type: 'array', - admin: { - description: - 'Cookies the site uses — shown on the cookie policy page () and per category in the detailed settings window. Fill it from a scan: Cookie review → Scan cookies (cookieScanner option), or ipal-consent-check → cookie-scan.', - initCollapsed: true, - }, - fields: [ - { - type: 'row', fields: [ - { name: 'name', type: 'text', admin: { width: '40%' }, required: true }, - { name: 'provider', type: 'text', admin: { description: 'e.g. Google, this site', width: '30%' } }, { - name: 'category', - type: 'select', - admin: { width: '30%' }, - defaultValue: 'necessary', - options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })), - required: true, + name: 'eyebrow', + type: 'text', + admin: { description: HIDDEN_HINT, placeholder: { en: 'Privacy & cookies', pl: 'Prywatność i cookies' } }, + label: { en: 'Label above title', pl: 'Etykieta nad tytułem' }, + localized: true, + }, + { + name: 'title', + type: 'text', + admin: { description: HIDDEN_HINT, placeholder: { en: 'We respect your privacy', pl: 'Dbamy o prywatność' } }, + label: { en: 'Title', pl: 'Tytuł' }, + localized: true, + }, + { + name: 'message', + type: 'textarea', + admin: { description: DEFAULT_HINT }, + label: { en: 'Message', pl: 'Treść' }, + localized: true, + }, + { + name: 'privacyLinkLabel', + type: 'text', + admin: { + description: { + en: 'Leave empty to use the title of the privacy policy page set in Site settings.', + pl: 'Zostaw puste, aby użyć tytułu strony polityki prywatności wskazanej w ustawieniach witryny.', + }, + placeholder: { en: 'Privacy policy', pl: 'Polityka prywatności' }, + }, + label: { en: 'Privacy link text', pl: 'Tekst linku' }, + localized: true, + }, + { + name: 'buttons', + type: 'group', + admin: { description: DEFAULT_HINT }, + fields: [ + { + type: 'row', + fields: [ + { name: 'acceptAll', type: 'text', admin: { placeholder: { en: 'Accept all', pl: 'Akceptuj wszystkie' } }, label: { en: 'Accept all', pl: 'Akceptuj wszystkie' }, localized: true }, + { name: 'reject', type: 'text', admin: { placeholder: { en: 'Reject', pl: 'Odrzuć' } }, label: { en: 'Reject', pl: 'Odrzuć' }, localized: true }, + { name: 'settings', type: 'text', admin: { placeholder: { en: 'Settings', pl: 'Ustawienia' } }, label: { en: 'Settings', pl: 'Ustawienia' }, localized: true }, + ], + }, + { + type: 'row', + fields: [ + // Not `save`: Mongoose reserves that path name and warns on every start/build. + { name: 'savePreferences', type: 'text', admin: { placeholder: { en: 'Save preferences', pl: 'Zapisz ustawienia' } }, label: { en: 'Save', pl: 'Zapisz' }, localized: true }, + { name: 'back', type: 'text', admin: { placeholder: { en: 'Back', pl: 'Wstecz' } }, label: { en: 'Back', pl: 'Wstecz' }, localized: true }, + { + name: 'close', + type: 'text', + admin: { + description: { en: 'Read aloud by screen readers for the ✕ button.', pl: 'Odczytywany przez czytniki ekranu dla przycisku ✕.' }, + placeholder: { en: 'Close', pl: 'Zamknij' }, + }, + label: { en: 'Close', pl: 'Zamknij' }, + localized: true, + }, + ], + }, + ], + label: { en: 'Buttons', pl: 'Przyciski' }, }, ], + label: { en: 'Banner', pl: 'Baner' }, + }, + { + fields: [ + { + name: 'settingsTitle', + type: 'text', + admin: { description: DEFAULT_HINT, placeholder: { en: 'Cookie settings', pl: 'Ustawienia cookies' } }, + label: { en: 'Title', pl: 'Tytuł' }, + localized: true, + }, + { + name: 'settingsDescription', + type: 'textarea', + admin: { + description: { + en: 'What cookies are for and that the choice can be changed later, or leave empty to hide it.', + pl: 'Do czego służą cookies i że wybór można później zmienić, lub zostaw puste, aby go nie pokazywać.', + }, + }, + label: { en: 'Introduction', pl: 'Wstęp' }, + localized: true, + }, + { + name: 'alwaysActiveLabel', + type: 'text', + admin: { + description: { + en: 'Shown next to necessary cookies; leave empty to show a locked switch instead.', + pl: 'Widoczne przy niezbędnych cookies; zostaw puste, aby pokazać zablokowany przełącznik.', + }, + placeholder: { en: 'Always active', pl: 'Zawsze aktywne' }, + }, + label: { en: 'Always active badge', pl: 'Oznaczenie „zawsze aktywne”' }, + localized: true, + }, + { + name: 'detailLabels', + type: 'group', + admin: { + description: { + en: 'Shown above the cookie list under each category; leave empty to use the default.', + pl: 'Widoczne nad listą cookies w każdej kategorii; zostaw puste, aby użyć domyślnej wartości.', + }, + }, + fields: [ + { + name: 'cookies', + type: 'text', + admin: { + description: { en: 'The number of cookies is added after it.', pl: 'Po tekście dodawana jest liczba cookies.' }, + placeholder: { en: 'Cookies used', pl: 'Używane cookies' }, + }, + label: { en: 'List toggle', pl: 'Rozwijanie listy' }, + localized: true, + }, + { + type: 'row', + fields: [ + { name: 'provider', type: 'text', admin: { placeholder: { en: 'Provider', pl: 'Dostawca' } }, label: { en: 'Provider', pl: 'Dostawca' }, localized: true }, + { name: 'purpose', type: 'text', admin: { placeholder: { en: 'Purpose', pl: 'Cel' } }, label: { en: 'Purpose', pl: 'Cel' }, localized: true }, + { name: 'duration', type: 'text', admin: { placeholder: { en: 'Duration', pl: 'Okres' } }, label: { en: 'Duration', pl: 'Okres' }, localized: true }, + ], + }, + ], + label: { en: 'Cookie list headings', pl: 'Nagłówki listy cookies' }, + }, + ], + label: { en: 'Settings window', pl: 'Okno ustawień' }, + }, + { + fields: [ + { + name: 'categories', + type: 'array', + admin: { + components: rowLabel(['title', 'key'], { en: 'Category', pl: 'Kategoria' }), + description: { + en: 'A category not listed here uses the default title and description.', + pl: 'Kategoria spoza listy używa domyślnego tytułu i opisu.', + }, + }, + fields: [ + { + name: 'key', + type: 'select', + label: { en: 'Category', pl: 'Kategoria' }, + options: consentCategoryOptions(), + required: true, + }, + { name: 'title', type: 'text', label: { en: 'Title', pl: 'Tytuł' }, localized: true }, + { name: 'description', type: 'textarea', label: { en: 'Description', pl: 'Opis' }, localized: true }, + ], + label: { en: 'Categories', pl: 'Kategorie' }, + labels: { plural: { en: 'Categories', pl: 'Kategorie' }, singular: { en: 'Category', pl: 'Kategoria' } }, + }, + ], + label: { en: 'Categories', pl: 'Kategorie' }, + }, + { + fields: [ + { + name: 'cookies', + type: 'array', + admin: { + components: rowLabel(['name'], { en: 'Cookie', pl: 'Plik cookie' }), + description: { + en: 'Shown on the cookie policy page and in the settings window; fill it from Cookie review.', + pl: 'Widoczna na stronie polityki cookies i w oknie ustawień; uzupełnij ją z przeglądu cookies.', + }, + initCollapsed: true, + }, + fields: [ + { + type: 'row', + fields: [ + { name: 'name', type: 'text', admin: { placeholder: '_ga', width: '40%' }, label: { en: 'Name', pl: 'Nazwa' }, required: true }, + { name: 'provider', type: 'text', admin: { placeholder: 'Google', width: '30%' }, label: { en: 'Provider', pl: 'Dostawca' } }, + { + name: 'category', + type: 'select', + admin: { width: '30%' }, + defaultValue: 'necessary', + label: { en: 'Category', pl: 'Kategoria' }, + options: consentCategoryOptions(), + required: true, + }, + ], + }, + { name: 'purpose', type: 'textarea', label: { en: 'Purpose', pl: 'Cel' }, localized: true }, + { + name: 'duration', + type: 'text', + admin: { placeholder: { en: '2 years', pl: '2 lata' } }, + label: { en: 'Duration', pl: 'Okres' }, + localized: true, + }, + ], + label: { en: 'Cookies', pl: 'Cookies' }, + labels: { plural: { en: 'Cookies', pl: 'Cookies' }, singular: { en: 'Cookie', pl: 'Cookie' } }, + }, + ], + label: { en: 'Cookie list', pl: 'Lista cookies' }, }, - { name: 'purpose', type: 'textarea', localized: true }, - { name: 'duration', type: 'text', admin: { description: 'e.g. "2 years", "session"' }, localized: true }, ], - labels: { plural: 'Cookies', singular: 'Cookie' }, }, ] diff --git a/src/globals/CookieSettings/index.ts b/src/globals/CookieSettings/index.ts index f24cfa2..79591b5 100644 --- a/src/globals/CookieSettings/index.ts +++ b/src/globals/CookieSettings/index.ts @@ -15,9 +15,9 @@ export function buildCookieSettings(): GlobalConfig { update: ({ req }) => userMeetsRole(req, 'editor'), // consent texts are legal copy — not for plain 'user' accounts }, admin: { - group: 'Settings', + group: { en: 'Privacy', pl: 'Prywatność' }, }, fields: cookieSettingsFields, - label: 'Cookie Settings', + label: { en: 'Cookie banner', pl: 'Baner cookies' }, } } diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts index 9bbaec5..0a548e4 100644 --- a/src/globals/Notifications/fields.ts +++ b/src/globals/Notifications/fields.ts @@ -1,12 +1,33 @@ import type { Field } from 'payload' -import { LIGHTBOX_FALLBACK } from '../../modules/lightbox/texts.js' +import { LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL } from '../../modules/lightbox/texts.js' +import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../../modules/notifications/defaults.js' + +const EN = NOTIFICATION_FALLBACK.form +const PL = NOTIFICATION_FALLBACK_PL.form + +/** A form text: the default in both languages is the placeholder. */ +const formText = ( + name: keyof typeof EN, + label: { en: string; pl: string }, + extra: { description?: { en: string; pl: string }; width?: string } = {}, +): Field => ({ + name, + type: 'text', + admin: { + placeholder: { en: EN[name], pl: PL[name] }, + ...(extra.description ? { description: extra.description } : {}), + ...(extra.width ? { width: extra.width } : {}), + }, + label, + localized: true, +}) /** * Fields for the Notifications global — localized user-facing texts for action * results (form submission outcomes, and future contexts). Every text is * localized: true so each language has its own value. Empty fields fall back to - * built-in English defaults (see modules/notifications/defaults). + * the built-in defaults of the page's language (see modules/notifications/defaults). * * Grouped per context. `form` holds the outcomes of submitForm; more groups * (e.g. `newsletter`, `system`) can be added the same way without touching @@ -18,91 +39,52 @@ export const notificationsFields: Field[] = [ name: 'form', type: 'group', admin: { - description: - 'Messages shown after a form is submitted. Leave a field empty to use the built-in default.', + description: { + en: 'Shown to visitors after they send a form; leave a field empty to use the default.', + pl: 'Widoczne dla odwiedzających po wysłaniu formularza; zostaw pole puste, aby użyć domyślnej wartości.', + }, }, fields: [ - { - name: 'success', - type: 'text', - admin: { placeholder: 'Thank you — your message has been sent.' }, - localized: true, - }, - { - name: 'error', - type: 'text', - admin: { placeholder: 'Something went wrong. Please try again later.' }, - localized: true, - }, - { - name: 'rateLimited', - type: 'text', - admin: { placeholder: 'Too many attempts. Please wait a moment and try again.' }, - localized: true, - }, - { - name: 'turnstile', - type: 'text', - admin: { placeholder: 'Captcha verification failed. Please try again.' }, - localized: true, - }, - { - name: 'validation', - type: 'text', - admin: { - description: - 'Shown on a validation error. Use {field} to insert the offending field name.', - placeholder: 'Please check the {field} field and try again.', + formText('success', { en: 'Sent', pl: 'Wysłano' }), + formText('error', { en: 'Error', pl: 'Błąd' }), + formText('validation', { en: 'Field error', pl: 'Błąd pola' }, { + description: { en: 'Use {field} for the field label.', pl: 'Użyj {field}, aby wstawić etykietę pola.' }, + }), + formText('consent', { en: 'Consent missing', pl: 'Brak zgody' }, { + description: { + en: 'Shown when the privacy policy box is not ticked.', + pl: 'Widoczny, gdy pole zgody na politykę prywatności nie jest zaznaczone.', }, - localized: true, - }, - { - name: 'consent', - type: 'text', - admin: { - description: 'Shown when the GDPR consent checkbox is left unchecked.', - placeholder: 'Please accept the privacy policy to continue.', - }, - localized: true, - }, - { - name: 'notFound', - type: 'text', - admin: { placeholder: 'This form is no longer available.' }, - localized: true, - }, + }), + formText('turnstile', { en: 'Spam check failed', pl: 'Błąd weryfikacji' }), + formText('rateLimited', { en: 'Too many attempts', pl: 'Zbyt wiele prób' }), + formText('notFound', { en: 'Form unavailable', pl: 'Formularz niedostępny' }), { type: 'row', fields: [ - { - name: 'next', - type: 'text', - admin: { description: 'Step-by-step forms: button to the next step.', placeholder: 'Next', width: '33%' }, - localized: true, - }, - { - name: 'back', - type: 'text', - admin: { description: 'Step-by-step forms: button to the previous step.', placeholder: 'Back', width: '33%' }, - localized: true, - }, - { - name: 'stepOf', - type: 'text', - admin: { description: 'Progress — {current} and {total} are replaced.', placeholder: 'Step {current} of {total}', width: '34%' }, - localized: true, - }, + formText('next', { en: 'Next button', pl: 'Przycisk „Dalej”' }, { width: '33%' }), + formText('back', { en: 'Back button', pl: 'Przycisk „Wstecz”' }, { width: '33%' }), + formText('stepOf', { en: 'Step counter', pl: 'Licznik kroków' }, { + description: { en: 'Use {current} and {total} for the numbers.', pl: 'Użyj {current} i {total}, aby wstawić liczby.' }, + width: '34%', + }), ], }, ], - label: 'Form messages', + label: { en: 'Forms', pl: 'Formularze' }, }, ] -const lightboxText = (name: keyof typeof LIGHTBOX_FALLBACK, width: string, description?: string): Field => ({ +const lightboxText = ( + name: keyof typeof LIGHTBOX_FALLBACK, + label: { en: string; pl: string }, + width: string, + description?: { en: string; pl: string }, +): Field => ({ name, type: 'text', - admin: { placeholder: LIGHTBOX_FALLBACK[name], width, ...(description ? { description } : {}) }, + admin: { placeholder: { en: LIGHTBOX_FALLBACK[name], pl: LIGHTBOX_FALLBACK_PL[name] }, width, ...(description ? { description } : {}) }, + label, localized: true, }) @@ -115,25 +97,34 @@ export const lightboxNotificationFields: Field = { name: 'lightbox', type: 'group', admin: { - description: 'Labels of the enlarged-image viewer, read by screen readers. Leave a field empty to use the built-in default.', + description: { + en: 'Read by screen readers in the enlarged image view; leave a field empty to use the default.', + pl: 'Odczytywane przez czytniki ekranu w podglądzie zdjęcia; zostaw pole puste, aby użyć domyślnej wartości.', + }, }, fields: [ { type: 'row', fields: [ - lightboxText('open', '50%', 'Button around a small image; its alt text follows after ": ".'), - lightboxText('dialog', '50%', 'Name of the viewer window.'), + lightboxText('open', { en: 'Enlarge button', pl: 'Przycisk powiększenia' }, '50%', { + en: 'The image description is added after it.', + pl: 'Po tekście dodawany jest opis zdjęcia.', + }), + lightboxText('dialog', { en: 'Viewer name', pl: 'Nazwa podglądu' }, '50%'), ], }, { type: 'row', fields: [ - lightboxText('previous', '25%'), - lightboxText('next', '25%'), - lightboxText('close', '25%'), - lightboxText('counter', '25%', '{current} and {total} are replaced.'), + lightboxText('previous', { en: 'Previous button', pl: 'Przycisk „Poprzednie”' }, '25%'), + lightboxText('next', { en: 'Next button', pl: 'Przycisk „Następne”' }, '25%'), + lightboxText('close', { en: 'Close button', pl: 'Przycisk „Zamknij”' }, '25%'), + lightboxText('counter', { en: 'Image counter', pl: 'Licznik zdjęć' }, '25%', { + en: 'Use {current} and {total} for the numbers.', + pl: 'Użyj {current} i {total}, aby wstawić liczby.', + }), ], }, ], - label: 'Lightbox', + label: { en: 'Image viewer', pl: 'Podgląd zdjęć' }, } diff --git a/src/globals/Notifications/index.ts b/src/globals/Notifications/index.ts index fd17385..d5663ef 100644 --- a/src/globals/Notifications/index.ts +++ b/src/globals/Notifications/index.ts @@ -4,7 +4,7 @@ import { userMeetsRole } from '../../modules/access/index.js' import { lightboxNotificationFields, notificationsFields } from './fields.js' /** - * Builds the Notifications global — localized action-result texts. Readable by + * Builds the Notifications global (shown as "Form messages") — localized action-result texts. Readable by * any authenticated panel user; server-side helpers read it with overrideAccess * so the frontend can resolve texts without a session. `lightbox` adds the * image-viewer labels (ipalKit `lightbox: true`). @@ -16,8 +16,8 @@ export function buildNotifications({ lightbox = false }: { lightbox?: boolean } read: () => true, // texts are public-facing (shown to end users) update: ({ req }) => userMeetsRole(req, 'editor'), }, - admin: { group: 'Settings' }, + admin: { group: { en: 'Forms', pl: 'Formularze' } }, fields: lightbox ? [...notificationsFields, lightboxNotificationFields] : notificationsFields, - label: 'Notifications', + label: { en: 'Form messages', pl: 'Komunikaty formularzy' }, } } diff --git a/src/globals/SiteIntegrations/components/MaskedField.tsx b/src/globals/SiteIntegrations/components/MaskedField.tsx index a79a9d8..7797b84 100644 --- a/src/globals/SiteIntegrations/components/MaskedField.tsx +++ b/src/globals/SiteIntegrations/components/MaskedField.tsx @@ -2,9 +2,11 @@ import type { TextFieldClientComponent } from 'payload' -import { FieldDescription, FieldLabel, useField } from '@payloadcms/ui' +import { FieldDescription, FieldLabel, useField, useTranslation } from '@payloadcms/ui' import { useState } from 'react' +import { ipalT } from '../../../modules/admin-i18n/t.js' + /** * Masked text input for sensitive values (SMTP password, R2 secret key, * Turnstile secret key, etc.). @@ -23,11 +25,12 @@ import { useState } from 'react' * Assigned via a field's admin.components.Field. Works on any `text` field. */ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { + const { t } = useTranslation() const { setValue, value } = useField({ path }) const [revealed, setRevealed] = useState(false) - const label = - typeof field?.label === 'string' ? field.label : (field?.name ?? path) + // A string or one string per language — FieldLabel / FieldDescription translate it. + const label = field?.label || field?.name || path const description = field?.admin?.description return ( @@ -60,11 +63,11 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { }} type="button" > - {revealed ? 'Hide' : 'Reveal'} + {ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')} - {description && typeof description === 'string' ? ( + {description && typeof description !== 'function' ? ( ) : null} diff --git a/src/globals/SiteIntegrations/components/TestEmailButton.tsx b/src/globals/SiteIntegrations/components/TestEmailButton.tsx index e7b0170..3ab291c 100644 --- a/src/globals/SiteIntegrations/components/TestEmailButton.tsx +++ b/src/globals/SiteIntegrations/components/TestEmailButton.tsx @@ -1,17 +1,21 @@ 'use client' +import { useTranslation } from '@payloadcms/ui' import { useState } from 'react' +import { ipalT } from '../../../modules/admin-i18n/t.js' + /** - * Admin UI: a small "send test email" tool for the SiteIntegrations email tab. + * Admin UI: a small "send test e-mail" tool for the SiteIntegrations e-mail tab. * Enter an address, click Send, and it POSTs to /api/ipal/test-email, which * sends through the currently-selected transport (SMTP or Graph). Shows the - * result inline so you can confirm delivery — or read the exact error — without - * leaving the panel. + * result inline so you can confirm delivery without leaving the panel. * - * Assigned via a `ui` field's admin.components.Field. + * Assigned via a `ui` field's admin.components.Field. Texts: `testEmail*` keys. */ export const TestEmailButton = () => { + const { t } = useTranslation() + const text = (key: Parameters[1], vars?: Record) => ipalT(t as never, key, vars) const [to, setTo] = useState('') const [status, setStatus] = useState< { kind: 'error'; msg: string } | { kind: 'idle' } | { kind: 'ok'; msg: string } | { kind: 'sending' } @@ -19,7 +23,7 @@ export const TestEmailButton = () => { const send = async () => { if (!to.trim()) { - setStatus({ kind: 'error', msg: 'Enter a recipient address.' }) + setStatus({ kind: 'error', msg: text('testEmailInvalidRecipient') }) return } setStatus({ kind: 'sending' }) @@ -32,27 +36,25 @@ export const TestEmailButton = () => { }) const data = await res.json() if (data.ok) { - setStatus({ kind: 'ok', msg: data.message ?? 'Test email sent.' }) + setStatus({ kind: 'ok', msg: data.message ?? text('testEmailSent', { to: to.trim() }) }) } else { - setStatus({ kind: 'error', msg: data.error ?? 'Send failed.' }) + setStatus({ kind: 'error', msg: data.error ?? text('testEmailFailed') }) } } catch { - setStatus({ kind: 'error', msg: 'Request failed. Is the server running?' }) + setStatus({ kind: 'error', msg: text('testEmailNoConnection') }) } } return (
- -

- Sends through the transport selected above. Save your changes first. -

+ +

{text('testEmailHint')}

setTo(e.target.value)} - placeholder="you@example.com" + placeholder="anna@example.com" style={{ flex: 1, minWidth: '220px' }} type="email" value={to} @@ -64,7 +66,7 @@ export const TestEmailButton = () => { style={{ whiteSpace: 'nowrap' }} type="button" > - {status.kind === 'sending' ? 'Sending…' : 'Send test'} + {status.kind === 'sending' ? text('testEmailSending') : text('testEmailSend')}
{status.kind === 'ok' && ( @@ -73,7 +75,7 @@ export const TestEmailButton = () => {

)} {status.kind === 'error' && ( -

+

✗ {status.msg}

)} diff --git a/src/globals/SiteIntegrations/fields/analytics.ts b/src/globals/SiteIntegrations/fields/analytics.ts index 104508b..f45c8a3 100644 --- a/src/globals/SiteIntegrations/fields/analytics.ts +++ b/src/globals/SiteIntegrations/fields/analytics.ts @@ -1,5 +1,7 @@ import type { Field } from 'payload' +import type { AdminText } from '../../../modules/admin-i18n/index.js' + import { validateAnalyticsId } from '../../../modules/analytics/idFormats.js' /** @@ -7,59 +9,61 @@ import { validateAnalyticsId } from '../../../modules/analytics/idFormats.js' * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only * after the matching consent category is granted (see modules/analytics). */ + +const GOOGLE: AdminText = { + en: "Follows the visitor's choice in the cookie banner (Google Consent Mode).", + pl: 'Uwzględnia wybór odwiedzającego w banerze cookies (Google Consent Mode).', +} +const AFTER_MARKETING: AdminText = { + en: 'Loads after the visitor accepts marketing cookies.', + pl: 'Wczytuje się po zaakceptowaniu przez odwiedzającego cookies marketingowych.', +} +const AFTER_ANALYTICS: AdminText = { + en: 'Loads after the visitor accepts analytics cookies.', + pl: 'Wczytuje się po zaakceptowaniu przez odwiedzającego cookies analitycznych.', +} + export const analyticsFields: Field[] = [ { name: 'ga4MeasurementId', type: 'text', - admin: { - description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)', - placeholder: 'G-XXXXXXXXXX', - }, + admin: { description: GOOGLE, placeholder: 'G-XXXXXXXXXX' }, + label: { en: 'Google Analytics 4 ID', pl: 'ID Google Analytics 4' }, validate: validateAnalyticsId('ga4MeasurementId', 'G-XXXXXXXXXX'), }, { name: 'gtmContainerId', type: 'text', - admin: { - description: 'Google Tag Manager container ID. (Google — Consent Mode)', - placeholder: 'GTM-XXXXXXX', - }, + admin: { description: GOOGLE, placeholder: 'GTM-XXXXXXX' }, + label: { en: 'Google Tag Manager ID', pl: 'ID Google Tag Manager' }, validate: validateAnalyticsId('gtmContainerId', 'GTM-XXXXXXX'), }, { name: 'metaPixelId', type: 'text', - admin: { - description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.', - placeholder: '1234567890123456', - }, + admin: { description: AFTER_MARKETING, placeholder: '1234567890123456' }, + label: { en: 'Meta Pixel ID', pl: 'ID Meta Pixel' }, validate: validateAnalyticsId('metaPixelId', '1234567890123456'), }, { name: 'clarityProjectId', type: 'text', - admin: { - description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.', - placeholder: 'abcdefghij', - }, + admin: { description: AFTER_ANALYTICS, placeholder: 'abcdefghij' }, + label: { en: 'Microsoft Clarity ID', pl: 'ID Microsoft Clarity' }, validate: validateAnalyticsId('clarityProjectId', 'abcdefghij'), }, { name: 'linkedInPartnerId', type: 'text', - admin: { - description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.', - placeholder: '1234567', - }, + admin: { description: AFTER_MARKETING, placeholder: '1234567' }, + label: { en: 'LinkedIn Insight Tag ID', pl: 'ID LinkedIn Insight Tag' }, validate: validateAnalyticsId('linkedInPartnerId', '1234567'), }, { name: 'tiktokPixelId', type: 'text', - admin: { - description: 'TikTok Pixel ID. Loads only after MARKETING consent.', - placeholder: 'CXXXXXXXXXXXXXXXXXXX', - }, + admin: { description: AFTER_MARKETING, placeholder: 'CXXXXXXXXXXXXXXXXXXX' }, + label: { en: 'TikTok Pixel ID', pl: 'ID TikTok Pixel' }, validate: validateAnalyticsId('tiktokPixelId', 'CXXXXXXXXXXXXXXXXXXX'), }, ] diff --git a/src/globals/SiteIntegrations/fields/smtp.ts b/src/globals/SiteIntegrations/fields/smtp.ts index dc4b1e1..b8b5a57 100644 --- a/src/globals/SiteIntegrations/fields/smtp.ts +++ b/src/globals/SiteIntegrations/fields/smtp.ts @@ -1,23 +1,33 @@ -import type { Field } from 'payload' +import type { Condition, Field } from 'payload' import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js' /** - * SMTP transport settings for outbound email. + * E-mail sending settings (SMTP, or Microsoft Graph set up on the server). * * Protected at the global level (SiteIntegrations requires an authenticated * user), so all fields — including the password — stay editable in the admin * panel while remaining inaccessible to anonymous API requests. */ + +// SMTP fields only matter with the SMTP transport — hidden while Graph is selected. +const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !== 'graph' + export const smtpFields: Field[] = [ // Status written by mailAdapter on every send (throttled) — banner on this tab. - buildIntegrationStatusBanner('emailStatus', 'Email'), + buildIntegrationStatusBanner( + 'emailStatus', + { en: 'E-mail sending', pl: 'Wysyłka e-mail' }, + { failing: 'statusEmailFailing', hint: 'statusEmailHint' }, + ), { name: 'emailTransport', type: 'select', admin: { - description: - 'How outbound email is sent. "Microsoft Graph" is only available when configured by the administrator (Intecion).', + description: { + en: 'Microsoft Graph works only when your administrator has set it up on the server.', + pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.', + }, // The Graph option only makes sense when agency credentials exist in env. // We can't read process.env in the admin UI directly, so a client project // that hasn't set up Graph should filter this option via integrationsFields @@ -25,62 +35,81 @@ export const smtpFields: Field[] = [ // availability at send time regardless of what's selected here. }, defaultValue: 'smtp', + label: { en: 'Sending method', pl: 'Sposób wysyłki' }, options: [ - { label: 'SMTP', value: 'smtp' }, - { label: 'Microsoft Graph (Exchange)', value: 'graph' }, + { label: { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' }, + { label: { en: 'Microsoft Graph (Exchange)', pl: 'Microsoft Graph (Exchange)' }, value: 'graph' }, ], }, { type: 'row', - admin: { - // Hide SMTP fields when Graph is selected — they're not used then. - condition: (_, siblingData) => siblingData?.emailTransport !== 'graph', - }, + fields: [ + { + name: 'smtpFromAddress', + type: 'email', + admin: { + description: { + en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.', + pl: 'Z tego adresu wychodzą e-maile; przy Microsoft Graph trafiają na niego odpowiedzi.', + }, + placeholder: 'info@example.com', + width: '50%', + }, + label: { en: 'Sender address', pl: 'Adres nadawcy' }, + }, + { + name: 'smtpFromName', + type: 'text', + admin: { + description: { + en: 'The name recipients see, e.g. the company name.', + pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy.', + }, + width: '50%', + }, + label: { en: 'Sender name', pl: 'Nazwa nadawcy' }, + }, + ], + }, + { + type: 'row', + admin: { condition: usesSmtp }, fields: [ { name: 'smtpHost', type: 'text', admin: { placeholder: 'smtp.example.com', width: '70%' }, + label: { en: 'Server', pl: 'Serwer' }, }, { name: 'smtpPort', type: 'number', - admin: { width: '30%' }, + admin: { + description: { en: 'Usually 587, or 465.', pl: 'Zwykle 587 lub 465.' }, + width: '30%', + }, defaultValue: 587, + label: { en: 'Port', pl: 'Port' }, }, ], }, { name: 'smtpUser', type: 'text', - admin: { - description: 'SMTP account username.', - }, + admin: { condition: usesSmtp }, + label: { en: 'User name', pl: 'Nazwa użytkownika' }, }, { name: 'smtpPassword', type: 'text', admin: { - description: 'SMTP account password.', // Masked in the UI (••••) — stored plaintext, readable for SMTP auth. components: { Field: '@intecion/ipal-kit/admin#MaskedField', }, + condition: usesSmtp, }, - }, - { - name: 'smtpFromAddress', - type: 'email', - admin: { - description: 'Default "from" address for outgoing mail.', - }, - }, - { - name: 'smtpFromName', - type: 'text', - admin: { - description: 'Default "from" display name.', - }, + label: { en: 'Password', pl: 'Hasło' }, }, { name: 'emailTest', diff --git a/src/globals/SiteIntegrations/fields/turnstile.ts b/src/globals/SiteIntegrations/fields/turnstile.ts index a753213..61d5224 100644 --- a/src/globals/SiteIntegrations/fields/turnstile.ts +++ b/src/globals/SiteIntegrations/fields/turnstile.ts @@ -3,7 +3,7 @@ import type { Field } from 'payload' import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js' /** - * Cloudflare Turnstile credentials. + * Cloudflare Turnstile credentials (spam protection on forms). * * siteKey is public (rendered in the widget); secretKey is used for * server-side verification. Both are protected at the global level @@ -12,24 +12,36 @@ import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../.. */ export const turnstileFields: Field[] = [ // Status written by the server when it verifies a form (checkTurnstile) — banner on this tab. - buildIntegrationStatusBanner('turnstileStatus', 'Turnstile'), + buildIntegrationStatusBanner( + 'turnstileStatus', + { en: 'Spam protection', pl: 'Ochrona przed spamem' }, + { failing: 'statusTurnstileFailing', hint: 'statusTurnstileHint' }, + ), { name: 'turnstileSiteKey', type: 'text', admin: { - description: 'Public site key rendered in the Turnstile widget.', + description: { + en: 'Public key of the Cloudflare Turnstile widget.', + pl: 'Klucz publiczny widżetu Cloudflare Turnstile.', + }, }, + label: { en: 'Site key', pl: 'Klucz witryny' }, }, { name: 'turnstileSecretKey', type: 'text', admin: { - description: 'Secret key used for server-side verification.', // Masked in the UI (••••) — stored plaintext, readable for verification. components: { Field: '@intecion/ipal-kit/admin#MaskedField', }, + description: { + en: 'Private key of the same widget; fill in both keys to turn spam protection on.', + pl: 'Klucz prywatny tego samego widżetu; uzupełnij oba klucze, aby włączyć ochronę.', + }, }, + label: { en: 'Secret key', pl: 'Klucz tajny' }, }, buildIntegrationStatusField('turnstileStatus'), ] diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index 90f21f1..cf788b1 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -36,18 +36,25 @@ export function buildSiteIntegrations({ update: ({ req }) => userMeetsRole(req, 'admin'), }, admin: { - group: 'Settings', + group: { en: 'Settings', pl: 'Ustawienia' }, }, fields: [ { type: 'tabs', tabs: [ - { fields: analyticsFields, label: 'Analytics' }, - { fields: turnstileFields, label: 'Turnstile' }, - { fields: smtpFields, label: 'SMTP' }, - { fields: indexNowFields, label: 'IndexNow' }, + { fields: analyticsFields, label: { en: 'Analytics', pl: 'Analityka' } }, + { + description: { + en: 'Cloudflare Turnstile checks that forms are sent by people, not bots.', + pl: 'Cloudflare Turnstile sprawdza, czy formularze wysyłają ludzie, a nie boty.', + }, + fields: turnstileFields, + label: { en: 'Spam protection', pl: 'Ochrona przed spamem' }, + }, + { fields: smtpFields, label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } }, + { fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } }, ...(additionalFields?.length - ? [{ fields: additionalFields, label: 'Custom' }] + ? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }] : []), ], }, @@ -68,6 +75,6 @@ export function buildSiteIntegrations({ }, ], }, - label: 'Site Integrations', + label: { en: 'Site integrations', pl: 'Integracje' }, } } diff --git a/src/globals/SiteSettings/fields/general.ts b/src/globals/SiteSettings/fields/general.ts index d60f8d3..8a5542f 100644 --- a/src/globals/SiteSettings/fields/general.ts +++ b/src/globals/SiteSettings/fields/general.ts @@ -5,14 +5,22 @@ import { validateFaviconField } from '../../../modules/seo/index.js' /** * General site identity fields. * Consumed by SEO/OG (siteName, defaultShareImage) and frontend (logo). + * + * Order (admin-ux §7): what visitors see first (name, description, images), + * then the profiles list, then the title format options in one row. The row is + * presentation only — data stays flat. */ export const generalFields: Field[] = [ { name: 'siteName', type: 'text', admin: { - description: 'Used in page titles and Open Graph metadata.', + description: { + en: 'Shown in page titles and when a link is shared.', + pl: 'Widoczna w tytułach stron i przy udostępnianiu linków.', + }, }, + label: { en: 'Site name', pl: 'Nazwa witryny' }, localized: true, required: true, }, @@ -20,76 +28,107 @@ export const generalFields: Field[] = [ name: 'siteDescription', type: 'textarea', admin: { - description: - 'Fallback meta description when a page has none. Also used for llms.txt and Open Graph.', + description: { + en: 'Shown in search results for pages without their own description.', + pl: 'Widoczny w wynikach wyszukiwania stron bez własnego opisu.', + }, }, + label: { en: 'Site description', pl: 'Opis witryny' }, localized: true, }, - { - name: 'titleOrder', - type: 'select', - admin: { - description: 'Which comes first in browser tabs.', - }, - defaultValue: 'page-first', - options: [ - { label: 'Page first — About Us | Acme', value: 'page-first' }, - { label: 'Site first — Acme | About Us', value: 'site-first' }, - ], - }, - { - name: 'titleSeparator', - type: 'select', - admin: { - description: 'Separates the page title from the site name in browser tabs.', - }, - defaultValue: '|', - options: [ - { label: 'Pipe — Page | Site', value: '|' }, - { label: 'Dash — Page – Site', value: '–' }, - { label: 'Hyphen — Page - Site', value: '-' }, - { label: 'Bullet — Page · Site', value: '·' }, - { label: 'Slash — Page / Site', value: '/' }, - ], - }, { name: 'logo', type: 'upload', + label: { en: 'Logo', pl: 'Logo' }, + relationTo: 'media', + }, + { + name: 'favicon', + type: 'upload', admin: { - description: 'Primary site logo.', + description: { + en: 'Square PNG or SVG, at least 48×48 px, shown in browser tabs and search results.', + pl: 'Kwadratowy plik PNG lub SVG, co najmniej 48×48 px, widoczny na kartach przeglądarki i w wynikach wyszukiwania.', + }, }, + hooks: { + // Warn the editor if the favicon is too small / not square for Google. + beforeValidate: [validateFaviconField], + }, + label: { en: 'Site icon (favicon)', pl: 'Ikona witryny (favicon)' }, relationTo: 'media', }, { name: 'defaultShareImage', type: 'upload', admin: { - description: 'Fallback Open Graph image when a page has none.', + description: { + en: 'Shown when a link to a page without its own image is shared.', + pl: 'Widoczny przy udostępnianiu linku do strony bez własnego obrazu.', + }, }, + label: { en: 'Share image', pl: 'Obraz udostępniania' }, relationTo: 'media', }, { name: 'sameAs', type: 'array', admin: { - description: - 'Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.', + description: { + en: 'Your business on Google, LinkedIn, Facebook and similar, so search engines and AI assistants recognise you.', + pl: 'Profile firmy w Google, LinkedIn, Facebooku itp., dzięki którym wyszukiwarki i asystenci AI rozpoznają firmę.', + }, initCollapsed: true, }, - fields: [{ name: 'url', type: 'text', required: true, validate: (v: unknown) => (typeof v === 'string' && /^https?:\/\/\S+$/.test(v)) || 'Full URL, e.g. https://www.linkedin.com/company/acme' }], - labels: { plural: 'Profiles', singular: 'Profile' }, + fields: [ + { + name: 'url', + type: 'text', + admin: { placeholder: 'https://www.linkedin.com/company/acme' }, + label: { en: 'Address (URL)', pl: 'Adres (URL)' }, + required: true, + validate: (v: unknown, { req }: { req?: { i18n?: { language?: string } } } = {}) => + (typeof v === 'string' && /^https?:\/\/\S+$/.test(v)) || + (req?.i18n?.language === 'pl' + ? 'Wpisz pełny adres, np. https://www.linkedin.com/company/acme' + : 'Enter a full address, e.g. https://www.linkedin.com/company/acme'), + }, + ], + label: { en: 'Official profiles', pl: 'Oficjalne profile' }, + labels: { plural: { en: 'Profiles', pl: 'Profile' }, singular: { en: 'Profile', pl: 'Profil' } }, }, { - name: 'favicon', - type: 'upload', - admin: { - description: - 'Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata.', - }, - hooks: { - // Warn the editor if the favicon is too small / not square for Google. - beforeValidate: [validateFaviconField], - }, - relationTo: 'media', + type: 'row', + fields: [ + { + name: 'titleOrder', + type: 'select', + admin: { + description: { + en: 'Order of the page name and the site name in the browser tab.', + pl: 'Kolejność nazwy strony i nazwy witryny na karcie przeglądarki.', + }, + }, + defaultValue: 'page-first', + label: { en: 'Title order', pl: 'Kolejność w tytule' }, + options: [ + { label: { en: 'Page first — About us | Acme', pl: 'Najpierw strona — O nas | Acme' }, value: 'page-first' }, + { label: { en: 'Site first — Acme | About us', pl: 'Najpierw witryna — Acme | O nas' }, value: 'site-first' }, + ], + }, + { + name: 'titleSeparator', + type: 'select', + defaultValue: '|', + label: { en: 'Title separator', pl: 'Separator w tytule' }, + options: [ + { label: { en: 'Pipe — Page | Site', pl: 'Kreska pionowa — Strona | Witryna' }, value: '|' }, + { label: { en: 'Dash — Page – Site', pl: 'Półpauza — Strona – Witryna' }, value: '–' }, + { label: { en: 'Hyphen — Page - Site', pl: 'Dywiz — Strona - Witryna' }, value: '-' }, + { label: { en: 'Bullet — Page · Site', pl: 'Kropka — Strona · Witryna' }, value: '·' }, + { label: { en: 'Slash — Page / Site', pl: 'Ukośnik — Strona / Witryna' }, value: '/' }, + ], + }, + ], }, ] diff --git a/src/globals/SiteSettings/fields/theme.ts b/src/globals/SiteSettings/fields/theme.ts index 5a929e5..e07a67c 100644 --- a/src/globals/SiteSettings/fields/theme.ts +++ b/src/globals/SiteSettings/fields/theme.ts @@ -12,32 +12,38 @@ export const themeFields: Field[] = [ name: 'defaultTheme', type: 'select', admin: { - description: 'Theme applied on a visitor’s first visit. System = the visitor’s device setting.', + description: { + en: 'Used on a visitor’s first visit.', + pl: 'Używany przy pierwszej wizycie.', + }, }, defaultValue: 'light', + label: { en: 'Default theme', pl: 'Domyślny motyw' }, options: [ - { label: 'Light', value: 'light' }, - { label: 'Dark', value: 'dark' }, - { label: 'System', value: 'system' }, + { label: { en: 'Light', pl: 'Jasny' }, value: 'light' }, + { label: { en: 'Dark', pl: 'Ciemny' }, value: 'dark' }, + { label: { en: 'Device setting', pl: 'Ustawienie urządzenia' }, value: 'system' }, ], required: true, }, { name: 'allowThemeToggle', type: 'checkbox', - admin: { - description: 'Show a light/dark switch on the site.', - }, defaultValue: true, + label: { en: 'Show theme switch', pl: 'Pokaż przełącznik motywu' }, }, { name: 'themeToggleLabel', type: 'text', admin: { condition: (data) => Boolean(data?.allowThemeToggle), - description: 'Name of the switch read by screen readers, e.g. "Dark mode".', + description: { + en: 'Read aloud by screen readers.', + pl: 'Odczytywana przez czytniki ekranu.', + }, + placeholder: { en: 'Dark mode', pl: 'Tryb ciemny' }, }, - label: 'Toggle label', + label: { en: 'Switch label', pl: 'Etykieta przełącznika' }, localized: true, }, ] diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index c526f6f..b4124f7 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -7,14 +7,14 @@ import { themeFields } from './fields/theme.js' type BuildSiteSettingsArgs = { /** Extra fields injected by the client project */ additionalFields?: Field[] - /** "Under construction" tab (developer tool) — given when the pages module is on. */ + /** "Maintenance" tab (maintenance mode) — given when the pages module is on. */ constructionFields?: Field[] - /** "Emails" tab — given with `forms: { emailLayout: true }`. */ + /** "E-mails" tab — given with `forms: { emailLayout: true }`. */ emailFields?: Field[] - /** "Search & AI" tab — search-engine verification, AI crawlers, llms.txt note (seo module). */ + /** "Search engines" tab — search-engine verification, AI assistants, llms.txt note (seo module). */ searchFields?: Field[] /** - * Fields for the "System Pages" tab — page assignments by role (homepage, + * Fields for the "System pages" tab — page assignments by role (homepage, * privacy policy, collection archives). Assembled by the caller, which is the * only place that knows which modules are enabled. The tab is omitted when * this is empty. @@ -33,7 +33,7 @@ type BuildSiteSettingsArgs = { * * Uses unnamed tabs — data stays flat (siteSettings.siteName, not * siteSettings.general.siteName). Client-provided fields land in their own - * "Custom" tab so core data paths never shift. + * "More" tab so core data paths never shift. Tab labels are presentation only. */ export function buildSiteSettings({ additionalFields, @@ -51,7 +51,7 @@ export function buildSiteSettings({ update: ({ req }) => userMeetsRole(req, 'editor'), }, admin: { - group: 'Settings', + group: { en: 'Settings', pl: 'Ustawienia' }, }, fields: [ { @@ -59,22 +59,24 @@ export function buildSiteSettings({ tabs: [ { fields: generalFields, - label: 'General', + label: { en: 'General', pl: 'Ogólne' }, }, { fields: themeFields, - label: 'Theme', + label: { en: 'Theme', pl: 'Motyw' }, }, ...(systemPageFields?.length - ? [{ fields: systemPageFields, label: 'System Pages' }] + ? [{ fields: systemPageFields, label: { en: 'System pages', pl: 'Strony systemowe' } }] : []), - ...(searchFields?.length ? [{ fields: searchFields, label: 'Search & AI' }] : []), - ...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []), - ...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []), - ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []), + ...(searchFields?.length ? [{ fields: searchFields, label: { en: 'Search engines', pl: 'Wyszukiwarki' } }] : []), + ...(emailFields?.length ? [{ fields: emailFields, label: { en: 'E-mails', pl: 'E-maile' } }] : []), + ...(constructionFields?.length + ? [{ fields: constructionFields, label: { en: 'Maintenance', pl: 'Prace techniczne' } }] + : []), + ...(additionalFields?.length ? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }] : []), ], }, ], - label: 'Site Settings', + label: { en: 'Site settings', pl: 'Ustawienia witryny' }, } } diff --git a/src/index.ts b/src/index.ts index 4d8590d..8611cf3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,9 @@ export { // components would load React UI into payload.config / the CLI (test/entryGraph). export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js' export type { A11yState } from './modules/accessibility/state.js' +export { applyAdminI18n } from './modules/admin-i18n/apply.js' +export { ADMIN_LANGUAGES, adminTexts, defineTexts, formatDateTime, formatNumber, ipalT } from './modules/admin-i18n/index.js' +export type { AdminLanguage, AdminText, AdminTextKey } from './modules/admin-i18n/index.js' export { rowLabel } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js' export type { AnalyticsConfig } from './modules/analytics/index.js' @@ -36,10 +39,15 @@ export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_CATEGORIES, + CONSENT_CATEGORY_LABELS, CONSENT_COOKIE, + CONSENT_FALLBACK, + CONSENT_FALLBACK_PL, CONSENT_LOG_SLUG, CONSENT_MAX_AGE, CONSENT_VERSION, + consentCategoryOptions, + consentFallback, DEFAULT_CONSENT, getConsentTexts, getCookieTable, @@ -176,12 +184,15 @@ export { custom, email, isEmail, + localizedRules, maxLength, minLength, pattern, required, + VALIDATION_MESSAGES, + validationMessages, } from './modules/forms/validators.js' -export type { Rule } from './modules/forms/validators.js' +export type { Rule, ValidationMessages } from './modules/forms/validators.js' export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js' export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). @@ -197,9 +208,9 @@ export { buildLocalizedPath, switchLocalePath } from './modules/i18n/localizedPa export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modules/i18n/negotiateLocale.js' export { resolveLocalized } from './modules/i18n/resolveLocalized.js' export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js' -export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js' +export type { IntegrationBannerTexts, IntegrationLabel, IntegrationState, IntegrationStatus } from './modules/integrations/index.js' // Image lightbox — pure helpers (components live in /client). -export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js' +export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js' export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from './modules/lightbox/index.js' export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js' export type { @@ -226,7 +237,7 @@ export { videoProps, } from './modules/media/index.js' export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './modules/media/index.js' -export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js' +export { getNotificationTexts, NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL, notificationFallback, resolveFormMessage } from './modules/notifications/index.js' export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js' export type { PagesOption, SystemPageRole } from './modules/pages/index.js' export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js' diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index fd58410..2f8d762 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -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 = { + 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, } diff --git a/src/modules/accessibility/AccessibilityWidget.tsx b/src/modules/accessibility/AccessibilityWidget.tsx index 21a3f02..08df12a 100644 --- a/src/modules/accessibility/AccessibilityWidget.tsx +++ b/src/modules/accessibility/AccessibilityWidget.tsx @@ -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 = { - 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; pl: Required } = { + 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 = { * * * - * 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 = { - * pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … }, - * de: { title: 'Barrierefreiheit', … }, - * } - * + * + * */ 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 = (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}
))} diff --git a/src/modules/accessibility/client.ts b/src/modules/accessibility/client.ts index ac7afec..1824efe 100644 --- a/src/modules/accessibility/client.ts +++ b/src/modules/accessibility/client.ts @@ -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' diff --git a/src/modules/accessibility/index.ts b/src/modules/accessibility/index.ts index d4d5d7b..f9a00db 100644 --- a/src/modules/accessibility/index.ts +++ b/src/modules/accessibility/index.ts @@ -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, diff --git a/src/modules/admin-i18n/apply.ts b/src/modules/admin-i18n/apply.ts new file mode 100644 index 0000000..a26d51b --- /dev/null +++ b/src/modules/admin-i18n/apply.ts @@ -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 }> = {} + 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), + }, + } +} diff --git a/src/modules/admin-i18n/define.ts b/src/modules/admin-i18n/define.ts new file mode 100644 index 0000000..6c20edf --- /dev/null +++ b/src/modules/admin-i18n/define.ts @@ -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>(texts: { en: T; pl: Record }) { + return texts +} diff --git a/src/modules/admin-i18n/index.ts b/src/modules/admin-i18n/index.ts new file mode 100644 index 0000000..1d1dd7a --- /dev/null +++ b/src/modules/admin-i18n/index.ts @@ -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' diff --git a/src/modules/admin-i18n/t.ts b/src/modules/admin-i18n/t.ts new file mode 100644 index 0000000..9add1cb --- /dev/null +++ b/src/modules/admin-i18n/t.ts @@ -0,0 +1,19 @@ +import type { AdminTextKey } from './texts/index.js' + +type TFunction = (key: never, vars?: Record) => 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..ipal.` wins over the plugin's. + */ +export function ipalT(t: TFunction, key: AdminTextKey, vars?: Record): 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)) diff --git a/src/modules/admin-i18n/texts/consent.ts b/src/modules/admin-i18n/texts/consent.ts new file mode 100644 index 0000000..44e5afa --- /dev/null +++ b/src/modules/admin-i18n/texts/consent.ts @@ -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: {}, +}) diff --git a/src/modules/admin-i18n/texts/content.ts b/src/modules/admin-i18n/texts/content.ts new file mode 100644 index 0000000..0e4c6fc --- /dev/null +++ b/src/modules/admin-i18n/texts/content.ts @@ -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}}', + }, +}) diff --git a/src/modules/admin-i18n/texts/index.ts b/src/modules/admin-i18n/texts/index.ts new file mode 100644 index 0000000..e9f9118 --- /dev/null +++ b/src/modules/admin-i18n/texts/index.ts @@ -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:`. */ +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 diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts new file mode 100644 index 0000000..9346091 --- /dev/null +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -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. anna@example.com.', + 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. anna@example.com.', + 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', + }, +}) diff --git a/src/modules/admin-i18n/texts/settings.ts b/src/modules/admin-i18n/texts/settings.ts new file mode 100644 index 0000000..6b0c1a1 --- /dev/null +++ b/src/modules/admin-i18n/texts/settings.ts @@ -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', + }, +}) diff --git a/src/modules/admin-ui/RowLabelComponent.tsx b/src/modules/admin-ui/RowLabelComponent.tsx index 1039781..9701538 100644 --- a/src/modules/admin-ui/RowLabelComponent.tsx +++ b/src/modules/admin-ui/RowLabelComponent.tsx @@ -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 /** 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>() + const { i18n, t } = useTranslation() for (const f of fields) { const text = toText(at(data, f)) if (text) {return {text.length > 60 ? `${text.slice(0, 57)}…` : text}} } - return {`${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`} + const name = + typeof fallback === 'string' + ? fallback + : fallback + ? ((fallback as Record)[i18n.language] ?? fallback.en ?? Object.values(fallback)[0]) + : ipalT(t, 'rowLabelItem') + return {`${name} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`} } diff --git a/src/modules/admin-ui/rowLabel.ts b/src/modules/admin-ui/rowLabel.ts index 589650c..2af7c85 100644 --- a/src/modules/admin-ui/rowLabel.ts +++ b/src/modules/admin-ui/rowLabel.ts @@ -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' } } } diff --git a/src/modules/analytics/idFormats.ts b/src/modules/analytics/idFormats.ts index 381b7d2..8ffd571 100644 --- a/src/modules/analytics/idFormats.ts +++ b/src/modules/analytics/idFormats.ts @@ -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}.` + } diff --git a/src/modules/blocks/sectionFields.ts b/src/modules/blocks/sectionFields.ts index 162bd7a..c9ed126 100644 --- a/src/modules/blocks/sectionFields.ts +++ b/src/modules/blocks/sectionFields.ts @@ -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
/ 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
. - * 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' }, } } diff --git a/src/modules/branding/adminGraphics.tsx b/src/modules/branding/adminGraphics.tsx index b0f9d05..0b3db41 100644 --- a/src/modules/branding/adminGraphics.tsx +++ b/src/modules/branding/adminGraphics.tsx @@ -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 }; 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' ? { diff --git a/src/modules/consent/CookieTable.tsx b/src/modules/consent/CookieTable.tsx index 9e8a5dc..9814d99 100644 --- a/src/modules/consent/CookieTable.tsx +++ b/src/modules/consent/CookieTable.tsx @@ -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> - /** 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 + /** 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 }) - * + * // 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 ( {caption ? : null} diff --git a/src/modules/consent/categoryLabels.ts b/src/modules/consent/categoryLabels.ts new file mode 100644 index 0000000..78da477 --- /dev/null +++ b/src/modules/consent/categoryLabels.ts @@ -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 = { + 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 })) diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index 8df8412..f2299cd 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -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, } } diff --git a/src/modules/consent/getConsentTexts.ts b/src/modules/consent/getConsentTexts.ts index 6cd063e..8c83e44 100644 --- a/src/modules/consent/getConsentTexts.ts +++ b/src/modules/consent/getConsentTexts.ts @@ -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 { const g = await getGlobal(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() } : {}), diff --git a/src/modules/consent/index.ts b/src/modules/consent/index.ts index b6265da..f88b078 100644 --- a/src/modules/consent/index.ts +++ b/src/modules/consent/index.ts @@ -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 { diff --git a/src/modules/consent/scanner/CookieScanButton.tsx b/src/modules/consent/scanner/CookieScanButton.tsx index c81e49b..6644d62 100644 --- a/src/modules/consent/scanner/CookieScanButton.tsx +++ b/src/modules/consent/scanner/CookieScanButton.tsx @@ -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(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} - {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 }) diff --git a/src/modules/consent/scanner/collection.ts b/src/modules/consent/scanner/collection.ts index cb4b8be..68c4eca 100644 --- a/src/modules/consent/scanner/collection.ts +++ b/src/modules/consent/scanner/collection.ts @@ -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', }, diff --git a/src/modules/consent/scanner/crawl/endpoints.ts b/src/modules/consent/scanner/crawl/endpoints.ts index ba8da18..621bc3a 100644 --- a/src/modules/consent/scanner/crawl/endpoints.ts +++ b/src/modules/consent/scanner/crawl/endpoints.ts @@ -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 }) } }, diff --git a/src/modules/consent/scanner/crawl/global.ts b/src/modules/consent/scanner/crawl/global.ts index 45802e5..2d3c9f6 100644 --- a/src/modules/consent/scanner/crawl/global.ts +++ b/src/modules/consent/scanner/crawl/global.ts @@ -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) 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) 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, }, diff --git a/src/modules/consent/scanner/crawl/ingest.ts b/src/modules/consent/scanner/crawl/ingest.ts index e11ea8d..148a55a 100644 --- a/src/modules/consent/scanner/crawl/ingest.ts +++ b/src/modules/consent/scanner/crawl/ingest.ts @@ -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, diff --git a/src/modules/consent/scanner/labels.ts b/src/modules/consent/scanner/labels.ts index f3ceafb..3b7992b 100644 --- a/src/modules/consent/scanner/labels.ts +++ b/src/modules/consent/scanner/labels.ts @@ -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. anna@example.com, jan@example.com.', 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. anna@example.com, jan@example.com.', 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', }, } diff --git a/src/modules/construction/ConstructionNotice.tsx b/src/modules/construction/ConstructionNotice.tsx index b398c12..99a997c 100644 --- a/src/modules/construction/ConstructionNotice.tsx +++ b/src/modules/construction/ConstructionNotice.tsx @@ -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. diff --git a/src/modules/construction/fields.ts b/src/modules/construction/fields.ts index 015d602..5ec4c9a 100644 --- a/src/modules/construction/fields.ts +++ b/src/modules/construction/fields.ts @@ -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, }, diff --git a/src/modules/content/archiveFields.ts b/src/modules/content/archiveFields.ts index 3e282e5..747971b 100644 --- a/src/modules/content/archiveFields.ts +++ b/src/modules/content/archiveFields.ts @@ -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 } +} diff --git a/src/modules/content/types.ts b/src/modules/content/types.ts index 8c45e49..709a49d 100644 --- a/src/modules/content/types.ts +++ b/src/modules/content/types.ts @@ -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'. */ diff --git a/src/modules/email/graphAdapter.ts b/src/modules/email/graphAdapter.ts index f7cbb12..b76d858 100644 --- a/src/modules/email/graphAdapter.ts +++ b/src/modules/email/graphAdapter.ts @@ -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 } } }, }) diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index adcebff..a27a0bb 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -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' }, diff --git a/src/modules/email/panelSmtpAdapter.ts b/src/modules/email/panelSmtpAdapter.ts index 6e3dafa..687604c 100644 --- a/src/modules/email/panelSmtpAdapter.ts +++ b/src/modules/email/panelSmtpAdapter.ts @@ -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 } } }, }) diff --git a/src/modules/email/sendEmail.ts b/src/modules/email/sendEmail.ts index 3e06dd5..dd8b771 100644 --- a/src/modules/email/sendEmail.ts +++ b/src/modules/email/sendEmail.ts @@ -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 } } } diff --git a/src/modules/email/test/testEmailEndpoint.ts b/src/modules/email/test/testEmailEndpoint.ts index 55e16a3..b2d1288 100644 --- a/src/modules/email/test/testEmailEndpoint.ts +++ b/src/modules/email/test/testEmailEndpoint.ts @@ -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 { + 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, '&').replace(//g, '>').replace(/"/g, '"') + 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[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: '

This is a test message from ipal-kit. If you received it, outbound email is configured correctly.

', - subject: 'ipal-kit — test email', - text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.', + html: `

${escapeHtml(text)}

`, + 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', diff --git a/src/modules/forms/builderBlocks.ts b/src/modules/forms/builderBlocks.ts index bd46679..64f1bc6 100644 --- a/src/modules/forms/builderBlocks.ts +++ b/src/modules/forms/builderBlocks.ts @@ -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(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) diff --git a/src/modules/forms/emailLayout.ts b/src/modules/forms/emailLayout.ts index c77c70e..f2d0ca6 100644 --- a/src/modules/forms/emailLayout.ts +++ b/src/modules/forms/emailLayout.ts @@ -114,7 +114,7 @@ ${footerLines ? `
{rows.map(([key, count]) => ( - - + + ))}
{caption}
!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, }, diff --git a/src/modules/forms/formAnalyticsFields.ts b/src/modules/forms/formAnalyticsFields.ts index f59d4d0..8d463bc 100644 --- a/src/modules/forms/formAnalyticsFields.ts +++ b/src/modules/forms/formAnalyticsFields.ts @@ -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' }, }, ] } diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 2ca4d27..c3c0c20 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -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 = { + 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:')` → our `{ en, pl }`; anything else unchanged. */ +function formBuilderText(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(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 + const out: Record = { ...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 + 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 + 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 = { + form: { en: 'Form', pl: 'Formularz' }, + submissionData: { en: 'Answers', pl: 'Odpowiedzi' }, + submissionUploads: { en: 'Files', pl: 'Pliki' }, +} +const SUBMISSION_ROW_LABELS: Record = { + 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 + }, }, }) } diff --git a/src/modules/forms/index.ts b/src/modules/forms/index.ts index e178006..4b85450 100644 --- a/src/modules/forms/index.ts +++ b/src/modules/forms/index.ts @@ -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' diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 7eb18dc..1f5106e 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -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 { + 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 + } +} diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index bd45bbc..2689fc7 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -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 /** * form-builder `beforeEmail` — change the e-mails before they go out. Runs after * the ipal layout when `emailLayout` is on. diff --git a/src/modules/forms/useBuilderForm.ts b/src/modules/forms/useBuilderForm.ts index 280d47e..fb2de7d 100644 --- a/src/modules/forms/useBuilderForm.ts +++ b/src/modules/forms/useBuilderForm.ts @@ -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) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts]) diff --git a/src/modules/forms/useForm.ts b/src/modules/forms/useForm.ts index 2966cd1..9cb3d7b 100644 --- a/src/modules/forms/useForm.ts +++ b/src/modules/forms/useForm.ts @@ -26,7 +26,10 @@ export type Validator = (values: T) => FormErrors type UseFormOptions> = { /** 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> = { export function useForm>(options: UseFormOptions) { 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>(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) } diff --git a/src/modules/forms/validators.ts b/src/modules/forms/validators.ts index f78eb9f..cf72204 100644 --- a/src/modules/forms/validators.ts +++ b/src/modules/forms/validators.ts @@ -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. anna@example.com.', + 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. anna@example.com.', + 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) => boolean, msg: string): Rule => diff --git a/src/modules/hooks/preventDeleteSystemPage.ts b/src/modules/hooks/preventDeleteSystemPage.ts index 2f85ddd..5cb293f 100644 --- a/src/modules/hooks/preventDeleteSystemPage.ts +++ b/src/modules/hooks/preventDeleteSystemPage.ts @@ -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, ) } diff --git a/src/modules/hooks/validateUniqueRole.ts b/src/modules/hooks/validateUniqueRole.ts index 1c7b673..81f2f93 100644 --- a/src/modules/hooks/validateUniqueRole.ts +++ b/src/modules/hooks/validateUniqueRole.ts @@ -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 + 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 | 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)?.[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, ) } diff --git a/src/modules/integrations/IntegrationAlerts.tsx b/src/modules/integrations/IntegrationAlerts.tsx index 0c04334..93a9a13 100644 --- a/src/modules/integrations/IntegrationAlerts.tsx +++ b/src/modules/integrations/IntegrationAlerts.tsx @@ -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 + /** Status groups to check: field name → label (one string, or one per language). */ + checks?: Record + /** Injected by Payload into admin server components. */ + i18n?: { language?: string; t?: (key: never, vars?: Record) => string } /** Injected by Payload into admin server components. */ payload?: Payload } +const DEFAULT_CHECKS: Record = { + 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 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', }} > - Integration problem — the site still works, but something needs attention. + {serverText(i18nLike, 'alertsHeading')}
    - {failing.map(({ label, message }) => ( -
  • + {failing.map(({ field, label, message }) => ( +
  • {label}: {message}
  • ))}
- Open Site Integrations → + {serverText(i18nLike, 'alertsLink')} ) diff --git a/src/modules/integrations/IntegrationStatusBanner.tsx b/src/modules/integrations/IntegrationStatusBanner.tsx index 9e0ff18..90e39bb 100644 --- a/src/modules/integrations/IntegrationStatusBanner.tsx +++ b/src/modules/integrations/IntegrationStatusBanner.tsx @@ -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) => ipalT(t as never, key as never, vars) + if (state === 'ok') { + const sinceText = date(since) return (
- ✓ {label} working{since ? ` since ${fmt(since)}` : ''}. + ✓ {sinceText ? text('statusWorkingSince', { date: sinceText, label: name }) : text('statusWorking', { label: name })}
) } + const codeKey = code ? STATUS_CODE_TEXTS[code] : undefined + const detail = codeKey ? text(codeKey) : message + const sinceText = date(since) + const checkedText = date(checkedAt) + return (
- {label} is not working — forms are accepted without this check. - {message ?
{message}
: null} + {text(texts.failing ?? 'statusFailing', { label: name })} + {detail ?
{detail}
: null}
- {code ? `Code: ${code}. ` : ''} - {since ? `Since ${fmt(since)}. ` : ''} - {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''} -
-
- 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(' ')}
+
{text(texts.hint ?? 'statusHint')}
) } diff --git a/src/modules/integrations/index.ts b/src/modules/integrations/index.ts index b84f1b0..5814704 100644 --- a/src/modules/integrations/index.ts +++ b/src/modules/integrations/index.ts @@ -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' diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts index 7bb39cb..751dd5b 100644 --- a/src/modules/integrations/status.ts +++ b/src/modules/integrations/status.ts @@ -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 "
{key}{fmt(count)}{label ? label(key) : {key}}{num(i18n, count)}
) : ( -

No data yet.

+

{tr(i18n, 'statsNoData')}

)}
) } -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 ( <> -

← All statistics

-

Visitor {visitorId}

+

{tr(i18n, 'statsBack')}

+

{tr(i18n, 'statsVisitorHeading')} {visitorId}

- {visits.length} visit{visits.length === 1 ? '' : 's'} recorded with analytics consent. To erase this - visitor’s data, filter Statistics → Visits by this visitor id and delete the results. + {plural(i18n, 'statsVisitorVisits', visits.length)} {tr(i18n, 'statsVisitorErase')}

{visits.map((v) => (
- {when(v.startedAt, timeZone)} + {formatDateTime(v.startedAt, lang, timeZone)} - {' '}· {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 })}` : ''}
    {(v.pages ?? []).map((p, i) => (
  1. - {p.p} {when(p.t, timeZone).split(', ').pop()} + {p.p} {timeOnly(p.t, lang, timeZone)}
  2. ))}
@@ -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 =

You do not have access to the statistics.

+ content =

{tr(i18n, 'statsNoAccess')}

} else if (visitorId) { - content = + content = } 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 = ( <> -

Statistics

-

- 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. -

+

{tr(i18n, 'statsTitle')}

+

{tr(i18n, 'statsIntro')}

-
{fmt(totals.visits)}Visits
-
{fmt(totals.views)}Page views
+
{num(i18n, totals.visits)}{visits}
+
{num(i18n, totals.views)}{tr(i18n, 'statsPageViews')}
- {totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}Pages per visit + {num(i18n, totals.visits ? totals.views / totals.visits : 0, { maximumFractionDigits: 1, minimumFractionDigits: 1 })} + {tr(i18n, 'statsPagesPerVisit')}
-
{Math.round(totals.bounceRate * 100)}%Single-page visits
-
{fmt(totals.consented)}Visits with analytics consent
+
+ {num(i18n, totals.bounceRate, { maximumFractionDigits: 0, style: 'percent' })} + {tr(i18n, 'statsSinglePageVisits')} +
+
{num(i18n, totals.consented)}{tr(i18n, 'statsConsentedVisits')}
-

Visits per day

- +

{tr(i18n, 'statsVisitsPerDay')}

+
- - - - + + + (key === '(direct)' ? tr(i18n, 'statsDirect') : {key})} + rows={stats.referrers} + title={tr(i18n, 'statsColReferrer')} + unit={visits} + /> + deviceLabel(i18n, key)} rows={stats.devices} title={tr(i18n, 'statsColDevice')} unit={visits} />
-

Visitor history (analytics consent only)

+

{tr(i18n, 'statsVisitorHistory')}

{visitors.length ? ( - - + + {visitors.map((v) => ( - - + + ))}
VisitorLast seen{tr(i18n, 'statsColVisitor')}{tr(i18n, 'statsColLastVisit')}
{v.visitorId}{when(v.lastAt, timeZone)}{v.visitorId}{formatDateTime(v.lastAt, lang, timeZone)}
) : ( -

No visitor has accepted analytics cookies yet.

+

{tr(i18n, 'statsNoVisitors')}

)}
diff --git a/src/modules/stats/admin/StatsWidget.tsx b/src/modules/stats/admin/StatsWidget.tsx index 399974d..36a8645 100644 --- a/src/modules/stats/admin/StatsWidget.tsx +++ b/src/modules/stats/admin/StatsWidget.tsx @@ -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 (
-

Visits per day

+

{tr(i18n, 'statsVisitsPerDay')}

- Last 30 days: {stats.totals.visits.toLocaleString('en-US')} visits, {stats.totals.views.toLocaleString('en-US')} page views ·{' '} - All statistics → + {tr(i18n, 'statsWidgetSummary', { views: num(i18n, stats.totals.views), visits: num(i18n, stats.totals.visits) })} ·{' '} + {tr(i18n, 'statsWidgetLink')}

- +
) } diff --git a/src/modules/stats/admin/VisitsChart.tsx b/src/modules/stats/admin/VisitsChart.tsx index ca98b22..b90d962 100644 --- a/src/modules/stats/admin/VisitsChart.tsx +++ b/src/modules/stats/admin/VisitsChart.tsx @@ -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[] }) { - {Number.isInteger(t) ? t : t.toFixed(1)} + {num(i18n, t, { maximumFractionDigits: 1 })} ))} @@ -51,12 +61,12 @@ export function VisitsChart({ days }: { days: StatsDay[] }) { const label = i % 7 === (days.length - 1) % 7 return ( - {`${d.day}: ${d.visits} visits, ${d.views} page views`} + {tr(i18n, 'statsChartDay', { day: dayLabel(d.day, lang, 'medium'), views: num(i18n, d.views), visits: num(i18n, d.visits) })} {h > 0 ? : null} {label ? ( - {shortDate(d.day)} + {dayLabel(d.day, lang, 'short')} ) : null} @@ -64,21 +74,21 @@ export function VisitsChart({ days }: { days: StatsDay[] }) { })}
- Table + {tr(i18n, 'statsChartTable')} - - - + + + {[...days].reverse().map((d) => ( - - - + + + ))} diff --git a/src/modules/stats/admin/statsI18n.ts b/src/modules/stats/admin/statsI18n.ts new file mode 100644 index 0000000..af03824 --- /dev/null +++ b/src/modules/stats/admin/statsI18n.ts @@ -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 } + +/** Payload passes `i18n` to admin server components; without it, English. */ +const englishOnly: StatsI18n = { + language: 'en', + t: ((key: string, vars?: Record) => { + const text = (adminTexts.en as Record)[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) => 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') +} diff --git a/src/modules/stats/collection.ts b/src/modules/stats/collection.ts index 437430f..1073e40 100644 --- a/src/modules/stats/collection.ts +++ b/src/modules/stats/collection.ts @@ -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, } } diff --git a/src/modules/storage/buildR2Storage.ts b/src/modules/storage/buildR2Storage.ts index 5a3608d..8e22d37 100644 --- a/src/modules/storage/buildR2Storage.ts +++ b/src/modules/storage/buildR2Storage.ts @@ -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 diff --git a/src/modules/turnstile/config.ts b/src/modules/turnstile/config.ts index 8e96d3c..136b540 100644 --- a/src/modules/turnstile/config.ts +++ b/src/modules/turnstile/config.ts @@ -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 = { - '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 = { - '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 = { + '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 => { 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' } } diff --git a/src/plugin.ts b/src/plugin.ts index 70f06a4..598c92d 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -9,6 +9,7 @@ import { applyGlobalOverrides } from './globals/overrides.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' +import { applyAdminI18n } from './modules/admin-i18n/apply.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js' import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js' @@ -242,6 +243,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- i18n --- config.localization = buildLocalizationConfig(options.i18n) + // Admin languages (en + pl unless the project set its own) and the plugin's texts. + config = applyAdminI18n(config) // --- access: inject roles into the client's auth collection --- if (options.access) { @@ -373,6 +376,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { ...(config.admin?.components?.views ?? {}), ipalStats: { Component: { path: '@intecion/ipal-kit/admin#StatsView', serverProps: viewProps }, + meta: { title: 'Statistics' }, path: '/stats', }, }, diff --git a/test/adminUx.test.ts b/test/adminUx.test.ts new file mode 100644 index 0000000..ff14994 --- /dev/null +++ b/test/adminUx.test.ts @@ -0,0 +1,237 @@ +import type { CollectionConfig, Config, Field, GlobalConfig } from 'payload' + +import { describe, expect, test } from 'vitest' + +import { applyAdminI18n } from '../src/modules/admin-i18n/apply.js' +import { adminTexts } from '../src/modules/admin-i18n/index.js' +import { ipalKit } from '../src/plugin.js' + +/** + * docs/dev/admin-ux.md, enforced: every admin string the plugin adds has an + * explicit English and Polish text, within the length limits, without + * developer words. + */ + +const LABEL_MAX = 30 +const DESCRIPTION_MAX = 120 +const OPTION_MAX = 40 +const TEXT_MAX = 160 +// Product names may push a label past 3 words ("LinkedIn Insight Tag ID"). +const PRODUCTS = /Google|Meta|Microsoft|LinkedIn|TikTok|Cloudflare|Bing|Yandex|IndexNow|Search Console|Turnstile|Clarity|Pixel/ +// Function calls, JSX tags, ENV_VARS, camelCase words, package/vendor names, "Empty →". +const JARGON = /\w\(|<[A-Z]|\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b|\b[a-z]+[A-Z][a-z][A-Za-z]*\b|ipal-|Intecion|→/ +// Abbreviations that end in a dot but don't end a sentence. +const ABBREVIATIONS = /\b(e\.g|i\.e|np|m\.in|tzw|ok|min|maks|max|etc)\./gi + +const i18n = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +const t = (en: string, pl: string) => ({ en, pl }) +const project = (): Config => + ({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'pages', fields: [{ name: 'title', type: 'text', label: t('Title', 'Tytuł') }] }, + { slug: 'posts', fields: [{ name: 'title', type: 'text', label: t('Title', 'Tytuł') }] }, + { slug: 'media', fields: [], upload: true }, + ], + secret: 'test', + }) as unknown as Config + +const fullConfig = () => + ipalKit({ + access: { authCollection: 'users' }, + consentLog: true, + content: { collections: [{ slug: 'posts' }] }, + cookieScanner: { crawl: { serviceUrl: 'http://crawler.test', siteUrl: 'http://site.test', token: 'x' } }, + forms: { emailLayout: true }, + i18n, + indexNow: true, + lightbox: true, + pages: { slug: 'pages' }, + seo: { collections: ['pages', 'posts'] }, + stats: true, + twoFactor: false, + } as never)(project()) + +type Problem = string +type Text = unknown + +const isText = (v: Text): v is { en: string; pl: string } => + typeof v === 'object' && v !== null && typeof (v as { en?: unknown }).en === 'string' && typeof (v as { pl?: unknown }).pl === 'string' + +const sentences = (s: string) => s.replace(ABBREVIATIONS, '$1').split(/[.!?](?:\s|$)/).filter((p) => p.trim()).length + +function checkText(where: string, kind: 'description' | 'label' | 'option', value: Text, problems: Problem[]) { + if (!isText(value)) { + problems.push(`${where}: ${kind} is not { en, pl } (${JSON.stringify(value)})`) + return + } + for (const lang of ['en', 'pl'] as const) { + const s = value[lang].trim() + if (!s) {problems.push(`${where}: empty ${kind} (${lang})`)} + if (JARGON.test(s)) {problems.push(`${where}: developer words in ${kind} (${lang}): "${s}"`)} + if (kind === 'label') { + const words = s.split(/\s+/).length + if (s.length > LABEL_MAX) {problems.push(`${where}: label over ${LABEL_MAX} chars (${lang}): "${s}"`)} + if (words > (PRODUCTS.test(s) ? 5 : 3)) {problems.push(`${where}: label over 3 words (${lang}): "${s}"`)} + } + if (kind === 'option' && s.length > OPTION_MAX) {problems.push(`${where}: option over ${OPTION_MAX} chars (${lang}): "${s}"`)} + if (kind === 'description') { + if (s.length > DESCRIPTION_MAX) {problems.push(`${where}: description over ${DESCRIPTION_MAX} chars (${lang}): "${s}"`)} + if (sentences(s) > 1) {problems.push(`${where}: description longer than one sentence (${lang}): "${s}"`)} + } + } +} + +function walk(fields: Field[], path: string, problems: Problem[]) { + for (const field of fields) { + const f = field as { admin?: Record } & Field & Record + const where = `${path}.${'name' in f && f.name ? String(f.name) : f.type}` + if (f.hidden || f.admin?.hidden || f.admin?.disabled) {continue} + + if (f.type === 'tabs') { + for (const tab of (f as unknown as { tabs: ({ fields: Field[] } & Record)[] }).tabs) { + const tabWhere = `${path}.tab(${String(tab.name ?? JSON.stringify(tab.label))})` + checkText(tabWhere, 'label', tab.label, problems) + if (tab.description) {checkText(tabWhere, 'description', tab.description, problems)} + walk(tab.fields, tabWhere, problems) + } + continue + } + if (f.type === 'row') { + walk(f.fields, path, problems) + continue + } + const visibleUi = f.type === 'ui' ? Boolean(f.label) : true + if (visibleUi && f.label !== false) {checkText(where, 'label', f.label, problems)} + if (f.admin?.description && typeof f.admin.description !== 'function') {checkText(where, 'description', f.admin.description, problems)} + if (Array.isArray(f.options)) { + for (const o of f.options as unknown[]) { + if (typeof o === 'object' && o) {checkText(`${where}[${String((o as { value: string }).value)}]`, 'option', (o as { label: Text }).label, problems)} + else {problems.push(`${where}: option "${String(o)}" has no label`)} + } + } + if (f.type === 'array') { + const labels = f.labels as { plural?: Text; singular?: Text } | undefined + checkText(`${where}.labels.singular`, 'label', labels?.singular, problems) + checkText(`${where}.labels.plural`, 'label', labels?.plural, problems) + } + if (f.type === 'blocks') { + for (const block of f.blocks as { fields: Field[]; labels?: { plural?: Text; singular?: Text }; slug: string }[]) { + checkText(`${where}.${block.slug}.labels.singular`, 'label', block.labels?.singular, problems) + checkText(`${where}.${block.slug}.labels.plural`, 'label', block.labels?.plural, problems) + walk(block.fields, `${where}.${block.slug}`, problems) + } + } + if ('fields' in f && Array.isArray(f.fields) && f.type !== 'blocks') {walk(f.fields as Field[], where, problems)} + } +} + +function checkGlobal(global: GlobalConfig, problems: Problem[]) { + checkText(`global ${global.slug}`, 'label', global.label, problems) + if (global.admin?.group) {checkText(`global ${global.slug} group`, 'label', global.admin.group, problems)} + if (global.admin?.description && typeof global.admin.description !== 'function') {checkText(`global ${global.slug}`, 'description', global.admin.description, problems)} + walk(global.fields, global.slug, problems) +} + +function checkCollection(collection: CollectionConfig, problems: Problem[]) { + checkText(`collection ${collection.slug} singular`, 'label', collection.labels?.singular, problems) + checkText(`collection ${collection.slug} plural`, 'label', collection.labels?.plural, problems) + if (collection.admin?.group) {checkText(`collection ${collection.slug} group`, 'label', collection.admin.group, problems)} + if (collection.admin?.description && typeof collection.admin.description !== 'function') {checkText(`collection ${collection.slug}`, 'description', collection.admin.description, problems)} + walk(collection.fields, collection.slug, problems) +} + +// Collections the plugin creates; fields of other plugins (form-builder, plugin-seo) are checked where ipal-kit sets them. +const PLUGIN_COLLECTIONS = ['consent-records', 'cookie-review', 'stats-visits'] + +describe('admin wording (docs/dev/admin-ux.md)', () => { + test('plugin globals: every visible text in en + pl, within limits', async () => { + const config = await fullConfig() + const problems: Problem[] = [] + for (const global of config.globals ?? []) {checkGlobal(global, problems)} + expect(problems).toEqual([]) + }) + + test('plugin collections: every visible text in en + pl, within limits', async () => { + const config = await fullConfig() + const problems: Problem[] = [] + const slugs = (config.collections ?? []).map((c) => c.slug) + for (const slug of PLUGIN_COLLECTIONS) { + const collection = config.collections?.find((c) => c.slug === slug || c.slug.startsWith(slug)) + expect(collection, `${slug} in ${slugs.join(', ')}`).toBeTruthy() + checkCollection(collection!, problems) + } + expect(problems).toEqual([]) + }) + + test('fields injected into project collections: en + pl, within limits', async () => { + const config = await fullConfig() + const problems: Problem[] = [] + for (const slug of ['users', 'pages', 'posts']) { + const collection = config.collections!.find((c) => c.slug === slug)! + walk(collection.fields, slug, problems) + } + expect(problems).toEqual([]) + }) + + test('form builder: blocks the plugin defines, en + pl, within limits', async () => { + const config = await fullConfig() + const problems: Problem[] = [] + const forms = config.collections!.find((c) => c.slug === 'forms')! + checkText('collection forms singular', 'label', forms.labels?.singular, problems) + checkText('collection forms plural', 'label', forms.labels?.plural, problems) + const blocksField = forms.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { fields: Field[]; labels?: { plural?: Text; singular?: Text }; slug: string }[] } + for (const block of blocksField.blocks) { + checkText(`forms.fields.${block.slug}.labels.singular`, 'label', block.labels?.singular, problems) + walk(block.fields, `forms.fields.${block.slug}`, problems) + } + expect(problems).toEqual([]) + }) + + test('component texts: same keys in en and pl, none empty, no developer words', () => { + const en = adminTexts.en as Record + const pl = adminTexts.pl as Record + expect(Object.keys(pl).sort()).toEqual(Object.keys(en).sort()) + const problems: Problem[] = [] + for (const [lang, texts] of Object.entries({ en, pl })) { + for (const [key, s] of Object.entries(texts)) { + if (!s.trim()) {problems.push(`${key} (${lang}) is empty`)} + if (s.length > TEXT_MAX) {problems.push(`${key} (${lang}) over ${TEXT_MAX} chars`)} + // The vendor credit (whiteLabel.credit) is the one place that names the vendor. + if (key !== 'brandingCredit' && JARGON.test(s.replace(/\{\{\w+\}\}/g, ''))) {problems.push(`${key} (${lang}) has developer words: "${s}"`)} + } + } + expect(problems).toEqual([]) + }) +}) + +describe('admin languages', () => { + test('English and Polish by default, with the plugin texts', async () => { + const config = await fullConfig() + expect(Object.keys(config.i18n?.supportedLanguages ?? {}).sort()).toEqual(['en', 'pl']) + const translations = config.i18n?.translations as Record }> + expect(translations.pl.ipal).toEqual(adminTexts.pl) + expect(translations.en.ipal).toEqual(adminTexts.en) + }) + + test("the project's languages and translations win", () => { + const de = { dateFNSKey: 'de', translations: {} } + const key = Object.keys(adminTexts.en)[0] + const config = applyAdminI18n({ + i18n: { supportedLanguages: { de } as never, translations: { de: { ipal: { [key]: 'Eigener Text' } } } as never }, + } as Config) + expect(Object.keys(config.i18n!.supportedLanguages!)).toEqual(['de']) + const translations = config.i18n!.translations as Record }> + expect(translations.de.ipal[key]).toBe('Eigener Text') + // Another key falls back to English, not to the raw key. + const other = Object.keys(adminTexts.en)[1] + expect(translations.de.ipal[other]).toBe((adminTexts.en as Record)[other]) + }) +}) diff --git a/test/drafts.test.ts b/test/drafts.test.ts index 1eee0b4..e769d69 100644 --- a/test/drafts.test.ts +++ b/test/drafts.test.ts @@ -83,7 +83,7 @@ describe('noindex protection', () => { const home = await payload.create({ collection: 'pages' as never, data: { slug: 'start', _status: 'published', title: 'Start' } as never }) const other = await payload.create({ collection: 'pages' as never, data: { slug: 'dziekujemy', _status: 'published', title: 'Dziękujemy' } as never }) await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never }) - await expect(payload.update({ id: home.id, collection: 'pages' as never, data: { noindex: true } as never })).rejects.toThrow(/Exclude from indexing/) + await expect(payload.update({ id: home.id, collection: 'pages' as never, data: { noindex: true } as never })).rejects.toThrow(/Hide from search engines/) const updated = (await payload.update({ id: other.id, collection: 'pages' as never, data: { noindex: true } as never })) as { noindex?: boolean } expect(updated.noindex).toBe(true) }) diff --git a/test/integration.test.ts b/test/integration.test.ts index dd965e5..c63c0a4 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -224,8 +224,9 @@ describe('one-call helpers — layout, page, GEO routes', () => { const shell = await h().getSiteShell('pl') expect(shell.turnstileSiteKey).toBeNull() expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String)) - expect(shell.formTexts).toMatchObject({ next: 'Next', stepOf: 'Step {current} of {total}' }) - expect(shell.lightboxTexts).toMatchObject({ close: 'Close', counter: '{current} / {total}' }) + // a Polish page gets the Polish defaults while the panel is empty + expect(shell.formTexts).toMatchObject({ next: 'Dalej', stepOf: 'Krok {current} z {total}' }) + expect(shell.lightboxTexts).toMatchObject({ close: 'Zamknij', counter: '{current} / {total}' }) expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization']) expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true) const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false }) @@ -319,7 +320,8 @@ describe('consent texts', () => { expect(empty.title).toBeUndefined() expect(empty.settingsDescription).toBeUndefined() expect(empty.alwaysActiveLabel).toBeUndefined() - expect(empty.buttons.close).toBe('Close') + expect(empty.buttons.close).toBe('Zamknij') // Polish default on a Polish page + expect((await getConsentTexts({ config, locale: 'en', payload, privacyPolicy: false })).buttons.close).toBe('Close') await payload.updateGlobal({ slug: 'cookie-settings' as never, @@ -354,10 +356,10 @@ describe('cookie table', () => { { name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }, ]) - // the same rows feed the detailed settings window, with English labels until the panel has them + // the same rows feed the detailed settings window, with the page language's default labels until the panel has them const texts = await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false }) expect(texts.cookies).toEqual([{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }]) - expect(texts.details).toEqual({ cookies: 'Cookies used', duration: 'Duration', provider: 'Provider', purpose: 'Purpose' }) + expect(texts.details).toEqual({ cookies: 'Używane cookies', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel' }) await payload.updateGlobal({ slug: 'cookie-settings' as never, diff --git a/test/lightbox.test.ts b/test/lightbox.test.ts index c372e3b..da27cae 100644 --- a/test/lightbox.test.ts +++ b/test/lightbox.test.ts @@ -94,6 +94,9 @@ describe('lightbox helpers', () => { expect(lightboxIndex(0, -1, 3, false)).toBe(0) expect(formatLightboxCounter('{current} z {total}', 2, 5)).toBe('2 z 5') expect(resolveLightboxTexts({ close: 'Zamknij', next: ' ', previous: null })).toEqual({ ...LIGHTBOX_FALLBACK, close: 'Zamknij' }) + // a Polish page falls back to Polish, any other language to English + expect(resolveLightboxTexts({ close: 'X' }, 'pl')).toMatchObject({ close: 'X', next: 'Następne zdjęcie' }) + expect(resolveLightboxTexts(null, 'de').next).toBe(LIGHTBOX_FALLBACK.next) }) test('Notifications gets the Lightbox group only when asked', () => { diff --git a/test/links.test.ts b/test/links.test.ts index 28402c6..06ca671 100644 --- a/test/links.test.ts +++ b/test/links.test.ts @@ -94,7 +94,11 @@ describe('project-defined link styles', () => { const { buildLinkField } = await import('../src/modules/links/buildLinkField.js') const field = buildLinkField({ appearances: ['primary', { label: 'Highlighted', value: 'highlight' }] }) const select = field.fields.find((f) => 'name' in f && f.name === 'appearance') as { defaultValue: string; options: unknown[] } - expect(select.options).toEqual([{ label: 'primary', value: 'primary' }, { label: 'Highlighted', value: 'highlight' }]) + // a default style named by value gets its panel label; the project's own label is kept + expect(select.options).toEqual([ + { label: { en: 'Main button', pl: 'Przycisk główny' }, value: 'primary' }, + { label: 'Highlighted', value: 'highlight' }, + ]) expect(select.defaultValue).toBe('primary') expect(resolveLink({ ...page('oferta'), appearance: 'highlight' }, opts)?.appearance).toBe('highlight') }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 5c6df52..fd405ae 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -148,12 +148,12 @@ describe('gap fixes: searchSettings, collection overrides', () => { const tabsOf = (config: Config) => { const settings = config.globals!.find((g) => g.slug === 'site-settings')! const tabs = settings.fields.find((f) => f.type === 'tabs') as { tabs: { label?: unknown }[] } - return tabs.tabs.map((t) => String(t.label)) + return tabs.tabs.map((t) => (t.label as { en?: string } | undefined)?.en ?? String(t.label)) } - test('searchSettings: false removes the Search & AI tab without `seo`', async () => { - expect(tabsOf(await ipalKit({ i18n, twoFactor: false })(base()))).toContain('Search & AI') - expect(tabsOf(await ipalKit({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search & AI') + test('searchSettings: false removes the Search engines tab without `seo`', async () => { + expect(tabsOf(await ipalKit({ i18n, twoFactor: false })(base()))).toContain('Search engines') + expect(tabsOf(await ipalKit({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search engines') }) test('searchSettings: a function shapes the fields; the top-level option wins over seo.searchSettings', async () => { @@ -165,11 +165,11 @@ describe('gap fixes: searchSettings, collection overrides', () => { })(base()) const settings = config.globals!.find((g) => g.slug === 'site-settings')! const tab = (settings.fields.find((f) => f.type === 'tabs') as { tabs: { fields: { name?: string }[]; label?: unknown }[] }).tabs.find( - (t) => t.label === 'Search & AI', + (t) => (t.label as { en?: string } | undefined)?.en === 'Search engines', )! expect(tab.fields.map((f) => f.name)).toEqual(['llmsIntro']) // the older seo.searchSettings still works alone - expect(tabsOf(await ipalKit({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search & AI') + expect(tabsOf(await ipalKit({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search engines') }) test('consentLog / stats collectionOverrides: an object merges access, a function takes over', async () => { diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts index 2fa829e..b4ae10f 100644 --- a/test/seoSearch.test.ts +++ b/test/seoSearch.test.ts @@ -32,7 +32,7 @@ afterEach(() => { vi.unstubAllEnvs() }) -describe('search verification (Site Settings → Search & AI)', () => { +describe('search verification (Site settings → Search engines)', () => { test('keeps the code from a bare value or a pasted tag', () => { expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ') expect(normalizeVerificationToken('')).toBe('Tok_9-x') @@ -289,24 +289,24 @@ describe('collectSiteIndex and llms.txt', () => { }) }) -describe('plugin: Search & AI tab', () => { +describe('plugin: Search engines tab', () => { const base = (): Config => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config const tabs = (c: Config) => { const settings = c.globals?.find((g) => g.slug === 'site-settings') - const field = settings?.fields[0] as { tabs: { label: string }[] } - return field.tabs.map((t) => t.label) + const field = settings?.fields[0] as { tabs: { label: { en: string } }[] } + return field.tabs.map((t) => t.label.en) } test('on by default, off with seo.searchSettings: false', async () => { const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base()) - expect(tabs(on)).toContain('Search & AI') + expect(tabs(on)).toContain('Search engines') const off = await ipalKit({ access: { authCollection: 'users' }, i18n: config, seo: { collections: [], searchSettings: false }, twoFactor: false, })(base()) - expect(tabs(off)).not.toContain('Search & AI') + expect(tabs(off)).not.toContain('Search engines') const custom = await ipalKit({ access: { authCollection: 'users' }, i18n: config, @@ -314,7 +314,7 @@ describe('plugin: Search & AI tab', () => { twoFactor: false, })(base()) const settings = custom.globals?.find((g) => g.slug === 'site-settings') - const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: string }[] }).tabs.find((t) => t.label === 'Search & AI') + const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: { en: string } }[] }).tabs.find((t) => t.label.en === 'Search engines') expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers']) }) }) diff --git a/test/storage.test.ts b/test/storage.test.ts index 1e0fe8e..13533ca 100644 --- a/test/storage.test.ts +++ b/test/storage.test.ts @@ -87,8 +87,8 @@ describe('buildR2Storage — read-only media (R2_PUBLIC_URL only, outside produc test('uploads and deletes are refused, metadata edits pass', async () => { const hooks = await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl' }) const guard = hooks!.beforeOperation[0] - expect(() => guard({ args: { req: { file: {} } }, operation: 'create' })).toThrow(/read-only/) - expect(() => guard({ args: { req: {} }, operation: 'delete' })).toThrow(/read-only/) + expect(() => guard({ args: { req: { file: {} } }, operation: 'create' })).toThrow(/cannot be uploaded or deleted/) + expect(() => guard({ args: { req: {} }, operation: 'delete' })).toThrow(/cannot be uploaded or deleted/) expect(() => guard({ args: { req: {} }, operation: 'update' })).not.toThrow() }) diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index d953475..65882e3 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { submitForm } from '../src/modules/forms/submitForm.js' +import { localizedRules, minLength, required } from '../src/modules/forms/validators.js' +import { notificationFallback } from '../src/modules/notifications/defaults.js' +import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js' import { UNKNOWN_IP_FACTOR } from '../src/modules/shared/rateLimit.js' import { fakePayload } from './helpers.js' @@ -171,6 +174,25 @@ describe('submitForm — other gates', () => { }) }) + test('a validation message names the field by its label, in the page language', async () => { + const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'email', blockType: 'email', label: 'Adres e-mail', required: true }] } } }) + const result = await submitForm({ data: { email: 'nope' }, formId: 'f', ip: nextIp(), locale: 'pl', maxPerMinute: 0, payload }) + expect(result).toEqual({ field: 'email', kind: 'invalid_format', label: 'Adres e-mail', reason: 'validation', success: false }) + expect(resolveFormMessage(result, notificationFallback('pl').form)).toBe('Sprawdź pole „Adres e-mail”.') + // no single field at fault → the generic error, never an empty {field} + expect(resolveFormMessage({ kind: 'unknown_fields', reason: 'validation', success: false }, notificationFallback('en').form)).toBe(notificationFallback('en').form.error) + }) + + test('validator messages: full sentences, Polish via localizedRules, own message wins', () => { + expect(required()('')).toBe('Fill in this field.') + expect(minLength(10)('abc')).toBe('Enter at least 10 characters.') + const pl = localizedRules('pl-PL') + expect(pl.required()('')).toBe('Uzupełnij to pole.') + expect(pl.minLength(2)('a')).toBe('Wpisz co najmniej 2 znaki.') + expect(pl.minLength(5)('a')).toBe('Wpisz co najmniej 5 znaków.') + expect(pl.email('Mój tekst')('x')).toBe('Mój tekst') + }) + test('the captcha field injected by the widget is not an unknown key', async () => { const { create, payload } = fakePayload({ forms }) const result = await submitForm({ @@ -200,8 +222,8 @@ describe('turnstileKeyProblem', () => { const { turnstileKeyProblem } = await import('../src/modules/turnstile/config.js') expect(turnstileKeyProblem({})).toBeNull() expect(turnstileKeyProblem({ turnstileSecretKey: 's', turnstileSiteKey: 'k' })).toBeNull() - expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toMatch(/Secret key is missing/) - expect(turnstileKeyProblem({ turnstileSecretKey: 's' })).toMatch(/Site key is missing/) + expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toMatch(/secret key is missing/) + expect(turnstileKeyProblem({ turnstileSecretKey: 's' })).toMatch(/site key is missing/) vi.stubEnv('TURNSTILE_SECRET_KEY', 's') expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toBeNull() })
DayVisitsPage views{tr(i18n, 'statsColDay')}{tr(i18n, 'statsVisits')}{tr(i18n, 'statsPageViews')}
{d.day}{d.visits}{d.views}{dayLabel(d.day, lang, 'medium')}{num(i18n, d.visits)}{num(i18n, d.views)}