diff --git a/dev/app/(payload)/admin/importMap.js b/dev/app/(payload)/admin/importMap.js index fce525e..03bd16f 100644 --- a/dev/app/(payload)/admin/importMap.js +++ b/dev/app/(payload)/admin/importMap.js @@ -28,6 +28,7 @@ import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997e import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { FaviconCheck as FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' @@ -71,6 +72,7 @@ export const importMap = { "@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#FaviconCheck": FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23, diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index b9562d7..367f94d 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -411,6 +411,11 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`, 9. **RSC by default.** `'use client'` only for state/interaction, in a separate file; the section stays a server component and passes data to it. Secrets: `import 'server-only'`. 10. **Blocks do not import `lib/*`** (cycle). Server-side data → `enhanceProps`. +11. **Next.js 16.4.1 or later** (minimum safe version). 16.0.0–16.4.0 have unauthenticated RCE and DoS + advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-p3m5-59mp-jv5r); Payload supports no patched + 15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.1) and make sure `sharp` resolves to + 0.35.5 or later (`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep. + **Check:** `pnpm ls next sharp` → next ≥ 16.4.1, sharp ≥ 0.35.5; `pnpm dev` prints no security-upgrade warning. --- @@ -630,8 +635,10 @@ empty fields, without guessing, without numbered slots. You design the schema fo `collectionOverrides`, component texts via `i18n.translations..ipal.` (keys: `adminTexts` from `@intecion/ipal-kit`). Building blocks for your own admin components: `ipalT`, `formatNumber`, `formatDateTime`, `defineTexts`, `ADMIN_LANGUAGES`, - `applyAdminI18n` (already applied by `ipalKit`), types `AdminText`, `AdminLanguage`, `AdminTextKey` - — details in i18n.md "Admin panel languages and texts". + `applyAdminI18n` (already applied by `ipalKit`), `adminDocumentTitle` + `` (`/admin`; + a custom view's tab title in the admin language — Payload's `meta.title` is one fixed string), + types `AdminText`, `AdminLanguage`, `AdminTextKey` — details in i18n.md "Admin panel languages and texts". + **Check:** Polish panel → the view's browser tab reads in Polish. 4. **No "just in case" fields.** Every field is displayed by the component; an empty optional field = the element does not render (the component handles it). Hide dependent fields: `admin.condition` (video fields only with `mediaType: 'video'`, diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index b893275..3ea0201 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -124,6 +124,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `MaskedField` | SMTP / Turnstile secrets | always | | `TestEmailButton` | Site integrations → SMTP | always | | `MetaDescriptionCheck` | below `meta.description` | `seo` and `descriptionCheck !== false` | +| `FaviconCheck` | below Site settings → Site icon (`afterInput`) | always (with the global); remove with a `globalOverrides['site-settings']` function | | `RowLabel` | array row labels (Cookie banner categories and cookie list; your own `rowLabel(...)`) | always | ## 3. What the project wires itself diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 5f8cb0b..06803c2 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -177,14 +177,15 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection, | Export | Import from | What it does / when | |---|---|---| -| `ConstructionNotice` | `@intecion/ipal-kit/client` | "Under construction" popup: `{ mode, classNames? }` — opens after a redirect from a blocked address (`?notice=construction`) and on a click on a link to an unavailable page; texts from the panel, renders nothing when the mode is off. In `[locale]/layout.tsx` with `mode={await getConstructionMode(locale)}`. | +| `ConstructionNotice` | `@intecion/ipal-kit/client` | "Under construction" popup: `{ mode, classNames?, locale?, closeLabel? }` — with no button text in the panel the button shows `×` and gets a screen-reader name in the page language ("Close" / "Zamknij"; `locale` defaults to `mode.locale`, `closeLabel` overrides the text); opens after a redirect from a blocked address (`?notice=construction`) and on a click on a link to an unavailable page; texts from the panel, renders nothing when the mode is off. In `[locale]/layout.tsx` with `mode={await getConstructionMode(locale)}`. | | `isPathAllowed(pathname, allowedPaths)` | `@intecion/ipal-kit` | Whether the path is allowed in under-construction mode (exact match, no trailing `/`) → `boolean`. `createPageRoute` uses it itself — by hand only in your own routes. | | `isPathVisibleIn(mode, pathname)` | `@intecion/ipal-kit` | `true` when the mode is off or the path is allowed — the rule behind `isPathVisible` from `createContentHelpers`. For your own routes when you already hold the `ConstructionMode`. | | `pathOf(url)` | `@intecion/ipal-kit` | Pathname of an absolute or relative URL — feed a result URL to a `PathVisibility` check. | | `constructionNoticeHref(homePath)` | `@intecion/ipal-kit` | Redirect address for a blocked page: `${homePath}?notice=construction`. `createPageRoute` uses it itself. | | `CONSTRUCTION_NOTICE_PARAM` | `@intecion/ipal-kit` | Name of the query parameter that opens the popup: `'notice'` (value `construction`). | -**Types:** `ConstructionMode` (root and `/client`) — `{ enabled, allowedPaths, homePath, texts }` from `getConstructionMode(locale)`; `PathVisibility` — `(path, locale) => boolean | Promise` (`isPathVisible` from `createContentHelpers`; the `isPathVisible` option of the Markdown, MCP and search routes); `ConstructionNoticeClassNames` (`/client`) — popup classes. +**Types:** `ConstructionMode` (root and `/client`) — `{ enabled, allowedPaths, homePath, locale, texts }` from `getConstructionMode(locale)`; +`CONSTRUCTION_CLOSE_LABEL`, `CONSTRUCTION_CLOSE_LABEL_PL`, `constructionCloseLabel(locale?)` (root and `/client`) — the close button's screen-reader name; `PathVisibility` — `(path, locale) => boolean | Promise` (`isPathVisible` from `createContentHelpers`; the `isPathVisible` option of the Markdown, MCP and search routes); `ConstructionNoticeClassNames` (`/client`) — popup classes. ## Content and routing (`content`) — details: `node_modules/@intecion/ipal-kit/docs/content.md` @@ -592,7 +593,11 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP | `buildAutoFillMetaHook(mapping?)` | `@intecion/ipal-kit` | `beforeChange` hook that fills empty `meta.title`/`meta.description` from content. The plugin wires it itself on the `seo.collections` collections (option `seo.autoFill`) — do not call. | | `injectAutoFillMeta(config, seo)` | `@intecion/ipal-kit` | Injects the hook above into the SEO collections. The plugin wires it itself — do not call. | | `SKIP_AUTO_FILL` | `@intecion/ipal-kit` | `'ipalSkipAutoFill'` — `context` key (`context: { [SKIP_AUTO_FILL]: true }`) that turns off meta auto-fill and the AI summary on save (migrations, scripts). | -| `validateFaviconField` | `@intecion/ipal-kit` | `FieldHook` that warns when the favicon is < 48×48 or not square. The plugin wires it itself on the favicon field in SiteSettings — call it only for your own favicon field. | +| `validateFaviconField` | `@intecion/ipal-kit` | `FieldHook` that logs a server warning when the favicon is < 48×48 or not square (never blocks the save). The plugin wires it itself on the favicon field in SiteSettings — call it only for your own favicon field. | +| `DocumentTitle` | `@intecion/ipal-kit/admin` | Client component `{ title }`: sets the browser-tab title of a custom admin view after load, so it follows the admin language (Payload's view `meta.title` is one fixed string). Render it in your view with a translated title; the statistics view uses it. | +| `adminDocumentTitle(title, titleSuffix?)` | `@intecion/ipal-kit` | `"Title - Suffix"` the way Payload builds a tab title — pass `req.payload.config.admin.meta.titleSuffix`. | +| `FaviconCheck` | `@intecion/ipal-kit/admin` | Hint under the site icon in Site settings: the chosen image is under 48×48 px or not square (text in the admin language, saving never blocked). Injected by the plugin; `pnpm generate:importmap`. Props: `fieldPath` (default the field it sits under), `mediaSlug` (`'media'`) — for your own favicon field: `admin.components.afterInput: [{ path: '@intecion/ipal-kit/admin#FaviconCheck', clientProps: { fieldPath: 'icon' } }]`. | +| `faviconProblems(media)`, `FAVICON_MIN_SIZE` | `@intecion/ipal-kit` | The check both use: `{ width, height, mimeType }` → `FaviconProblem[]` (`{ key: 'faviconTooSmall' \| 'faviconNotSquare', width, height }`); SVG and unknown sizes pass. Types: `FaviconProblem` (root), `FaviconCheckProps` (`/admin`). | | `MetaDescriptionCheck` | `@intecion/ipal-kit/admin` | Hint below the meta description in the SEO tab (description duplicated from the global or another document). Injected by the plugin; after turning the option on, `pnpm generate:importmap`. | **Types:** `PageMetadata`, `OgImage` — `buildMetadata` result and OG image; `SeoMeta`, `SeoOption`, `AutoFillMapping` — the `meta` group, the plugin's `seo` option and the auto-fill mapping; `SiteMetaConfig` — `readSiteMetaConfig` result; `RobotsOptions`, `RobotsRules` — `buildRobots` options and result; `AiBotsPolicy` (`'allow' \| 'block-training' \| 'disallow' \| false`), `AiBotRule` (`{ userAgent, access: 'allow' \| 'disallow' }`, `aiBotRules`, wins over the policy); `VerificationMetadata` — `verificationFrom` result; `SitemapEntry`, `SitemapRouteOptions`, `SitemapStyleOptions` — sitemap entry, handler and style options; `CollectSiteIndexArgs`, `SiteIndexEntry` — `collectSiteIndex` arguments and entry; `NoSnippetProps` (`/client`, `/rsc`) — `NoSnippet` props. diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 10f4803..30e38b5 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -39,6 +39,8 @@ legacy-peer-deps=true pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \ @payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss ``` +**Next.js 16.4.1 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, AGENT.md §4 item 11): +`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5` when create-payload-app gave you an older one. `nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own `lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical, plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then @@ -46,7 +48,8 @@ plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`. **Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists; -`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `ls src/middleware.ts` → not found. +`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.1, +sharp ≥ 0.35.5; `ls src/middleware.ts` → not found. 404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1). **Turn off / override.** `@payloadcms/storage-s3` and `@clocklimited/payload-2fa` are optional peers — only unneeded diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index 3e55af3..3120c81 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -82,6 +82,16 @@ the banner → `` and remove the copy. With `d `buildGlobalRevalidateHook({ revalidatePath })`; `consentFieldName` passed only because the option was ignored → `forms.consentFieldName` works now; your own seed guard / upsert code → `@intecion/ipal-kit/seed` (`createSeeder`). +**Every upgrade — Next.js 16.4.1 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.1 → +`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify +(a new image ships the fixed next and sharp). **Check:** `pnpm dev` prints no security-upgrade warning. + +**→ after 1.13.0 (admin follow-ups):** `pnpm payload generate:importmap` — new panel component +`@intecion/ipal-kit/admin#FaviconCheck` (hint under Site settings → Site icon). **Check:** pick a 32×32 PNG as the +site icon → a warning appears under the field; saving still works. Nothing else to change: the statistics tab title, +the cookie scanner's integration names and the maintenance notice's close button now follow the language by themselves +(`` already passes it). + ## 2. Inventory (no code changes) For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result. diff --git a/docs/construction.md b/docs/construction.md index a75fb36..8297978 100644 --- a/docs/construction.md +++ b/docs/construction.md @@ -11,7 +11,7 @@ subpages (e.g. a brief), and everything else is blocked — no code changes, one |---|---| | Site under construction | turns the mode on | | Pages still available | pages that still open; **the home page is always available** | -| Notice title / text / Close button label | popup content (per language); empty button → `×` | +| Notice title / text / Close button label | popup content (per language); empty button → `×` with a screen-reader name in the page language ("Close" / "Zamknij") | Fields in the SiteSettings global: group `construction` → `enabled`, `allowedPages` (relationship to the pages collection, hasMany), `title`, `message`, `buttonLabel` (localized). @@ -77,7 +77,9 @@ New fields in Site settings = a migration in the project (`payload migrate:creat Markdown / MCP without the filter even with the mode on: `createContentHelpers({ markdown: { isPathVisible: () => true }, mcp: { isPathVisible: () => true } })`; sitemap / llms.txt without the filter: `createContentHelpers({ underConstructionSeo: false })`. -- **Override:** popup look through `classNames` (`overlay`, `dialog`, `title`, `message`, `button`); +- **Override:** the `×` button's screen-reader name through `closeLabel` (default by `locale`, which defaults to + `mode.locale` from `getConstructionMode(locale)`; `constructionCloseLabel(locale)` is the default); + popup look through `classNames` (`overlay`, `dialog`, `title`, `message`, `button`); texts in the admin panel. Your own rule = your own `isPathVisible` function in the options above or in `createSearchRoute`. Access/hooks of the Site settings global: `ipalKit({ globalOverrides: { 'site-settings': … } })`. - **Extend:** `getConstructionMode(locale)` + `isPathVisibleIn` / `isPathAllowed` / `pathOf` / diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md index ebcb7ed..035f962 100644 --- a/docs/cookie-scanner.md +++ b/docs/cookie-scanner.md @@ -52,7 +52,12 @@ Status changes work in the list's bulk edit too. Deleting review entries is admi by the plugin. Labels are in English and Polish and follow the editor's admin language; `cookieScanner.labels` adds -languages or changes text. +languages or changes text. The built-in integrations without a product name (Cookie banner, Admin panel +login, Language choice, Built-in statistics) take their names from the shared admin texts +(`adminTexts`, keys `cookieIntegration*`, and `cookieSourceProject` for your own declarations), so the scan +box lists them in the editor's language; the *Source* stored on a review entry is in the language of +whoever ran the scan (English for a site check). Rename one through `cookieScanner.integrations` +(`label: { en: '…', pl: '…' }`). ## What the plugin declares @@ -120,7 +125,7 @@ run the tests, commit. | Key | Default | What it does | |---|---|---| | `declarations` | `[]` | The project's own cookies (custom embeds, chat, YouTube): `CookieDeclaration[]`, always part of a scan | -| `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label`, `declarations`, `isEnabled(ctx)`) | +| `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label` — one string or `{ en, pl, … }` per admin language, `declarations`, `isEnabled(ctx)`) | | `database` | `true` | `false` = no Open Cookie Database lookup | | `databaseCategories` | table above | Partial map from database category to consent category | | `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status | @@ -169,7 +174,7 @@ ipalKit({ cookieScanner: { integrations: (defaults) => [...defaults, chat] } }) | | | |---|---| -| `GET /api/ipal/cookie-scan` | `{ ok, integrations: [{ key, label }] }` — what a scan covers | +| `GET /api/ipal/cookie-scan` | `{ ok, integrations: [{ key, label }] }` — what a scan covers; `label` in the admin language of the request | | `POST /api/ipal/cookie-scan` | body `{ names?: string[] \| string }` (newline or comma separated, up to 200, names with spaces, `;`, `,` or `=` dropped) → `{ ok, summary: { created, updated, unchanged, unknown }, integrations }` | | Access | editor and up (`userMeetsRole`; without `access` every logged-in account), or `cookieScanner.access`; otherwise `403` | diff --git a/docs/i18n.md b/docs/i18n.md index 914b6f1..fd2238a 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -410,6 +410,13 @@ separate. The panel's language is what each user picks in *Account → Language* format in the admin language; `defineTexts({ en, pl })` declares a text set whose Polish keys must match the English ones; `ADMIN_LANGUAGES` lists the plugin's languages; `applyAdminI18n(config)` is the config step itself (already applied by `ipalKit`). +- **Browser-tab title of a custom admin view:** Payload takes a view's `meta.title` as one + plain string and never translates it (its custom-view metadata ignores `i18n`), so the + server-rendered title stays in that one language. Render `` + (`@intecion/ipal-kit/admin`) in the view with the translated title; after the page loads + the tab follows the admin language. `adminDocumentTitle(title, config.admin.meta.titleSuffix)` + builds the same "Title - Suffix" Payload would. The statistics view does this already: + its tab reads *Statystyki* in the Polish panel. - **Wording rules** for every label you add: [dev/admin-ux.md](./dev/admin-ux.md). - **Verify:** switch *Account → Language* to Polski — every plugin global, collection and view reads in Polish; `pnpm test` runs `test/adminUx.test.ts` in the plugin. diff --git a/docs/seo.md b/docs/seo.md index 2034933..c086a23 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -418,9 +418,16 @@ favicon field. SVG → scales; PNG → should be ≥48×48 (validation warns, se ### Enforcing the size (validation) -The favicon field in SiteSettings has the `validateFaviconField` validation — it warns -the editor on save if the favicon is <48×48 or not square. The editor -sees a warning instead of silently uploading a favicon Google will not show. +The favicon field in SiteSettings shows a hint right under it (`FaviconCheck`, `/admin`) +as soon as the editor picks an image under 48×48 px or one that is not square — in the +admin language, without blocking the save. The same check (`faviconProblems`) runs on +save in `validateFaviconField` and goes to the server log. + +- **Wire:** nothing beyond `pnpm payload generate:importmap` (the plugin adds the component). +- **Your own favicon field:** `admin.components.afterInput: [{ path: '@intecion/ipal-kit/admin#FaviconCheck', clientProps: { fieldPath: 'icon', mediaSlug: 'media' } }]`. +- **Turn off:** a `globalOverrides['site-settings']` function that drops `afterInput` from the field. +- **Texts:** `i18n.translations..ipal.faviconTooSmall` / `faviconNotSquare` (`{{width}}`, `{{height}}`). +- **Verify:** Site settings → Site icon → choose a 32×32 PNG → the warning appears; save still works. ### Organization JSON-LD (branding) diff --git a/docs/stats.md b/docs/stats.md index 47a7cca..83a4d3f 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -53,6 +53,8 @@ Adds: - `POST /api/ipal/hit`, - the **`/stats`** view (default `/admin/stats`; it uses `ipalKit({ adminRoute })`, not `routes.admin` set by hand in the config) + a nav link *Statistics overview* (`StatsNavLink`, hidden for users who cannot read `stats-visits`), + its browser tab reads *Statistics* / *Statystyki* in the admin language (set after load through + `DocumentTitle`, because Payload's view `meta.title` is one fixed string — i18n.md), - a 30-day chart on the dashboard (`StatsWidget`), - `STATS_SLUG` (`'stats-visits'`) from `@intecion/ipal-kit` — for your own queries. diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 4f45171..55feabe 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -7,12 +7,15 @@ */ export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js' export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js' +export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js' export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js' export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js' export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js' export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' +export { FaviconCheck } from '../modules/seo/FaviconCheck.js' +export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js' export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js' export { StatsNavLink } from '../modules/stats/admin/StatsNavLink.js' export { StatsView } from '../modules/stats/admin/StatsView.js' diff --git a/src/exports/client.ts b/src/exports/client.ts index 2eac05d..6e2bdfa 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -25,6 +25,7 @@ export { export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from '../modules/consent/client.js' export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js' export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js' +export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js' export type { ConstructionMode } from '../modules/construction/types.js' export { BuilderForm } from '../modules/forms/BuilderForm.js' export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js' diff --git a/src/globals/SiteSettings/fields/general.ts b/src/globals/SiteSettings/fields/general.ts index 8a5542f..a78f4de 100644 --- a/src/globals/SiteSettings/fields/general.ts +++ b/src/globals/SiteSettings/fields/general.ts @@ -46,13 +46,15 @@ export const generalFields: Field[] = [ name: 'favicon', type: 'upload', admin: { + // Warns under the field when the chosen icon is too small or not square (never blocks saving). + components: { afterInput: ['@intecion/ipal-kit/admin#FaviconCheck'] }, 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. + // Logs the same check on the server (the panel shows it through FaviconCheck). beforeValidate: [validateFaviconField], }, label: { en: 'Site icon (favicon)', pl: 'Ikona witryny (favicon)' }, diff --git a/src/index.ts b/src/index.ts index 8611cf3..a551f3f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,7 +24,7 @@ export { 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 { ADMIN_LANGUAGES, adminDocumentTitle, 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' @@ -123,6 +123,7 @@ export type { ResolvedCrawlConfig, } from './modules/consent/scanner/index.js' export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js' +export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from './modules/construction/texts.js' export type { ConstructionMode } from './modules/construction/types.js' export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js' export { pathOf } from './modules/construction/visibility.js' @@ -290,7 +291,8 @@ export { injectAutoFillMeta, } from './modules/seo/index.js' export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js' -export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js' +export { buildIconsMetadata, buildOrganizationJsonLd, FAVICON_MIN_SIZE, faviconProblems, sameAsUrls, validateFaviconField } from './modules/seo/index.js' +export type { FaviconProblem } from './modules/seo/index.js' export { buildNoindexField } from './modules/seo/index.js' export { buildSpeakableJsonLd } from './modules/seo/index.js' export { buildSummaryField, SKIP_AUTO_FILL } from './modules/seo/index.js' diff --git a/src/modules/admin-i18n/DocumentTitle.tsx b/src/modules/admin-i18n/DocumentTitle.tsx new file mode 100644 index 0000000..aadc0cd --- /dev/null +++ b/src/modules/admin-i18n/DocumentTitle.tsx @@ -0,0 +1,27 @@ +'use client' +import { useEffect } from 'react' + +/** + * Sets the browser-tab title of a custom admin view in the admin language. + * + * Payload takes a custom view's `meta.title` as one plain string and does not + * translate it, so the server-rendered title stays in English. The view + * renders this with its translated title (server side, from `req.i18n`) and + * the tab follows the editor's language once the page has loaded. + * + * On a full page load Next streams the view's metadata in after hydration and + * writes the English title back, so the title is re-applied whenever the head + * changes while the view is open. + */ +export function DocumentTitle({ title }: { title: string }) { + useEffect(() => { + const apply = () => { + if (document.title !== title) {document.title = title} + } + apply() + const observer = new MutationObserver(apply) + observer.observe(document.head, { characterData: true, childList: true, subtree: true }) + return () => observer.disconnect() + }, [title]) + return null +} diff --git a/src/modules/admin-i18n/index.ts b/src/modules/admin-i18n/index.ts index 1d1dd7a..ccb605e 100644 --- a/src/modules/admin-i18n/index.ts +++ b/src/modules/admin-i18n/index.ts @@ -1,6 +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 { adminDocumentTitle, 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 index 9add1cb..66ab7d8 100644 --- a/src/modules/admin-i18n/t.ts +++ b/src/modules/admin-i18n/t.ts @@ -17,3 +17,6 @@ export const formatNumber = (n: number, language: string) => new Intl.NumberForm /** 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)) + +/** The tab title Payload builds for a view: its title plus `admin.meta.titleSuffix`. */ +export const adminDocumentTitle = (title: string, titleSuffix?: null | string) => (titleSuffix ? `${title} ${titleSuffix}` : title) diff --git a/src/modules/admin-i18n/texts/consent.ts b/src/modules/admin-i18n/texts/consent.ts index 44e5afa..ae61938 100644 --- a/src/modules/admin-i18n/texts/consent.ts +++ b/src/modules/admin-i18n/texts/consent.ts @@ -2,6 +2,18 @@ import { defineTexts } from '../define.js' /** Admin component texts — consent. Placeholders use Payload's {{name}} syntax. */ export const consentTexts = defineTexts({ - en: {}, - pl: {}, + en: { + cookieIntegrationAdmin: 'Admin panel login', + cookieIntegrationConsent: 'Cookie banner', + cookieIntegrationLocale: 'Language choice', + cookieIntegrationStats: 'Built-in statistics', + cookieSourceProject: 'Project', + }, + pl: { + cookieIntegrationAdmin: 'Logowanie do panelu', + cookieIntegrationConsent: 'Baner cookies', + cookieIntegrationLocale: 'Wybór języka', + cookieIntegrationStats: 'Wbudowane statystyki', + cookieSourceProject: 'Projekt', + }, }) diff --git a/src/modules/admin-i18n/texts/settings.ts b/src/modules/admin-i18n/texts/settings.ts index 6b0c1a1..7d2de9c 100644 --- a/src/modules/admin-i18n/texts/settings.ts +++ b/src/modules/admin-i18n/texts/settings.ts @@ -4,8 +4,12 @@ import { defineTexts } from '../define.js' export const settingsTexts = defineTexts({ en: { brandingCredit: 'Technology supported by Intecion.com', + faviconNotSquare: 'The icon is not square ({{width}}×{{height}} px), so it may be cropped in tabs and search results.', + faviconTooSmall: 'The icon is {{width}}×{{height}} px. Google shows icons of at least 48×48 px; upload a larger one.', }, pl: { brandingCredit: 'Technologię wspiera Intecion.com', + faviconNotSquare: 'Ikona nie jest kwadratowa ({{width}}×{{height}} px), więc może być przycięta na kartach i w wynikach wyszukiwania.', + faviconTooSmall: 'Ikona ma {{width}}×{{height}} px. Google pokazuje ikony od 48×48 px; wgraj większą.', }, }) diff --git a/src/modules/consent/scanner/endpoint.ts b/src/modules/consent/scanner/endpoint.ts index cd4fdc0..ee813ce 100644 --- a/src/modules/consent/scanner/endpoint.ts +++ b/src/modules/consent/scanner/endpoint.ts @@ -1,9 +1,9 @@ import type { Endpoint, PayloadRequest } from 'payload' -import type { CookieScanContext, CookieScannerOptions } from './types.js' +import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from './types.js' import { userMeetsRole } from '../../access/predicates.js' -import { DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js' +import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js' import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js' export const COOKIE_SCAN_PATH = '/ipal/cookie-scan' @@ -18,14 +18,16 @@ export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: const allowed = async (req: PayloadRequest) => options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor') const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS - const list = (items: { key: string; label: string }[]) => items.map(({ key, label }) => ({ key, label })) + // Names in the admin language of the editor who asks. + const list = (items: CookieIntegration[], req: PayloadRequest) => + items.map((i) => ({ key: i.key, label: integrationLabel(i, req.i18n?.language) })) return [ { handler: async (req) => { if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })} const enabled = await enabledCookieIntegrations(integrations, await cookieScanContext(req.payload, plugin, req)) - return Response.json({ integrations: list(enabled), ok: true }) + return Response.json({ integrations: list(enabled, req), ok: true }) }, method: 'get', path: COOKIE_SCAN_PATH, @@ -41,7 +43,7 @@ export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: } try { const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req }) - return Response.json({ integrations: list(enabled), ok: true, summary }) + return Response.json({ integrations: list(enabled, req), ok: true, summary }) } catch (err) { req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`) return Response.json({ ok: false }, { status: 500 }) diff --git a/src/modules/consent/scanner/integrations.ts b/src/modules/consent/scanner/integrations.ts index fc4a713..19def69 100644 --- a/src/modules/consent/scanner/integrations.ts +++ b/src/modules/consent/scanner/integrations.ts @@ -1,9 +1,12 @@ +import type { AdminTextKey } from '../../admin-i18n/texts/index.js' import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './types.js' +import { adminTexts } from '../../admin-i18n/texts/index.js' import { validAnalyticsId } from '../../analytics/idFormats.js' import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js' import { getTurnstileConfig } from '../../turnstile/config.js' import { CONSENT_COOKIE } from '../storage.js' +import { textFor } from './merge.js' /** A tag ID from Site Integrations is filled in and valid. */ const hasId = (field: string) => (ctx: CookieScanContext) => @@ -16,6 +19,11 @@ const months = (n: number) => T(`${n} months`, `${n} mies.`) const YEAR = T('1 year', '1 rok') const TWO_YEARS = T('2 years', '2 lata') const SITE = 'This site' +/** A name from the shared admin texts, in every admin language the plugin ships. */ +const A = (key: AdminTextKey) => ({ en: adminTexts.en[key], pl: adminTexts.pl[key] }) + +/** Source name of the project's own `cookieScanner.declarations`. */ +export const PROJECT_SOURCE = A('cookieSourceProject') /** * Cookies of everything the plugin itself injects — one place per integration. @@ -37,7 +45,7 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ ], isEnabled: () => true, key: 'consent', - label: 'Cookie banner', + label: A('cookieIntegrationConsent'), }, { declarations: (ctx) => [ @@ -52,7 +60,7 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ ], isEnabled: () => true, key: 'admin', - label: 'Admin panel login', + label: A('cookieIntegrationAdmin'), }, { declarations: [ @@ -67,7 +75,7 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ ], isEnabled: (ctx) => ctx.plugin.localeCount > 1, key: 'locale', - label: 'Language choice', + label: A('cookieIntegrationLocale'), }, { declarations: [ @@ -85,7 +93,7 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ ], isEnabled: (ctx) => ctx.plugin.stats, key: 'stats', - label: 'Built-in statistics', + label: A('cookieIntegrationStats'), }, { declarations: [ @@ -281,6 +289,11 @@ export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [ }, ] +/** An integration's name in one admin language (English when that language is missing). */ +export function integrationLabel(integration: Pick, language = 'en'): string { + return textFor(integration.label, language) ?? '' +} + /** An integration's declarations for this project. */ export function declarationsOf(integration: CookieIntegration, ctx: CookieScanContext): CookieDeclaration[] { return typeof integration.declarations === 'function' ? integration.declarations(ctx) : integration.declarations diff --git a/src/modules/consent/scanner/scan.ts b/src/modules/consent/scanner/scan.ts index f041773..3f4e596 100644 --- a/src/modules/consent/scanner/scan.ts +++ b/src/modules/consent/scanner/scan.ts @@ -13,7 +13,7 @@ import type { import { COOKIE_REVIEW_SLUG } from './collection.js' import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js' -import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js' +import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS, integrationLabel, PROJECT_SOURCE } from './integrations.js' import { mergeCookieReview, suggestionFor } from './merge.js' /** Most names one scan looks up — the panel field is for a handful, not a dump. */ @@ -102,14 +102,18 @@ export async function collectCookieFindings({ if (!found.has(key)) {found.set(key, f)} return key } - for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))} + // Source names are stored in the admin language of whoever runs the scan. + const project = integrationLabel({ label: PROJECT_SOURCE }, ctx.language) + for (const d of declarations) {add(fromDeclaration(d, 'project', project))} for (const integration of enabled) { - for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integration.label))} + for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integrationLabel(integration, ctx.language)))} } const known = [ - ...declarations.map((d) => ({ d, detail: 'Project', source: 'project' as const })), - ...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))), + ...declarations.map((d) => ({ d, detail: project, source: 'project' as const })), + ...integrations.flatMap((i) => + declarationsOf(i, ctx).map((d) => ({ d, detail: integrationLabel(i, ctx.language), source: 'integration' as const })), + ), ] const index = database ? await loadCookieDatabase() : null for (const raw of names) { @@ -247,7 +251,7 @@ export async function cookieScanContext( } catch { // No such global (project replaced it) — integrations keyed on its IDs count as off. } - return { integrations, payload, plugin } + return { integrations, language: req?.i18n?.language ?? 'en', payload, plugin } } /** diff --git a/src/modules/consent/scanner/types.ts b/src/modules/consent/scanner/types.ts index f3ddf5a..d0703fa 100644 --- a/src/modules/consent/scanner/types.ts +++ b/src/modules/consent/scanner/types.ts @@ -34,6 +34,8 @@ export type CookieDeclaration = { export type CookieScanContext = { /** SiteIntegrations (depth 0); `{}` when it can't be read. */ integrations: Record + /** Admin language of the request (`req.i18n.language`); names stored by a scan use it. Default `'en'`. */ + language?: string payload: BasePayload /** Plugin options that switch modules on. */ plugin: { localeCount: number; stats: boolean } @@ -50,8 +52,8 @@ export type CookieIntegration = { isEnabled: (ctx: CookieScanContext) => boolean | Promise /** Stable id, e.g. `ga4`. */ key: string - /** Shown in the panel, e.g. `Google Analytics 4`. */ - label: string + /** Shown in the panel, e.g. `Google Analytics 4`, or per admin language: `{ en: 'Chat', pl: 'Czat' }`. */ + label: LocalizedText } /** Where a review entry's suggestion came from. `manual` = added by hand in the panel. */ diff --git a/src/modules/construction/ConstructionNotice.tsx b/src/modules/construction/ConstructionNotice.tsx index 99a997c..2cf9b12 100644 --- a/src/modules/construction/ConstructionNotice.tsx +++ b/src/modules/construction/ConstructionNotice.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react' import type { ConstructionMode } from './types.js' import { isPathAllowed } from './logic.js' +import { constructionCloseLabel } from './texts.js' import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js' export type ConstructionNoticeClassNames = { @@ -22,12 +23,26 @@ export type ConstructionNoticeClassNames = { * available — the click is cancelled. Closes with its button or Escape. * Renders nothing while the mode is off. * - * Unstyled (classNames, like CookieBanner); texts come from the panel. + * Unstyled (classNames, like CookieBanner); texts come from the panel. With no + * button text set, the button shows "×" and gets a screen-reader name in the + * page language ("Close" / "Zamknij"): `locale`, else `mode.locale`. * * // [locale]/layout.tsx * */ -export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) { +export function ConstructionNotice({ + classNames: cn = {}, + closeLabel, + locale, + mode, +}: { + classNames?: ConstructionNoticeClassNames + /** Screen-reader name of the "×" button. Default: "Close" / "Zamknij" by page language. */ + closeLabel?: string + /** Page language. Default: `mode.locale` (set by getConstructionMode). */ + locale?: string + mode: ConstructionMode +}) { const [open, setOpen] = useState(false) const buttonRef = useRef(null) const titleId = useId() @@ -76,7 +91,13 @@ export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?:
{mode.texts.title ?

{mode.texts.title}

: null} {mode.texts.message ?

{mode.texts.message}

: null} -
diff --git a/src/modules/construction/texts.ts b/src/modules/construction/texts.ts new file mode 100644 index 0000000..878545e --- /dev/null +++ b/src/modules/construction/texts.ts @@ -0,0 +1,7 @@ +/** Screen-reader name of the notice's close button when the panel sets no button text ("×" is shown). */ +export const CONSTRUCTION_CLOSE_LABEL = 'Close' +export const CONSTRUCTION_CLOSE_LABEL_PL = 'Zamknij' + +/** Close label for a page language: Polish for 'pl' / 'pl-PL', English for anything else. */ +export const constructionCloseLabel = (locale?: string): string => + locale?.toLowerCase().startsWith('pl') ? CONSTRUCTION_CLOSE_LABEL_PL : CONSTRUCTION_CLOSE_LABEL diff --git a/src/modules/construction/types.ts b/src/modules/construction/types.ts index dab0ce3..5acf637 100644 --- a/src/modules/construction/types.ts +++ b/src/modules/construction/types.ts @@ -8,6 +8,8 @@ export type ConstructionMode = { enabled: boolean /** Homepage in the current language — blocked addresses redirect here (with the notice). */ homePath: string + /** Page language the mode was read for (getConstructionMode(locale)); picks the notice's default texts. */ + locale?: string /** Notice texts from the panel, in the current language. Empty = not set. */ texts: { button?: string; message?: string; title?: string } } diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 735705f..a01982e 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -735,7 +735,7 @@ export function createContentHelpers({ const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/') const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale) const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown } - if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }} + if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, locale, texts: {} }} const configured = await getConfiguredLocales() const paths = await Promise.all( @@ -753,6 +753,7 @@ export function createContentHelpers({ allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))], enabled: true, homePath, + locale, texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)), } }) diff --git a/src/modules/seo/FaviconCheck.tsx b/src/modules/seo/FaviconCheck.tsx new file mode 100644 index 0000000..7987118 --- /dev/null +++ b/src/modules/seo/FaviconCheck.tsx @@ -0,0 +1,78 @@ +'use client' +import { useConfig, useFormFields, useTranslation } from '@payloadcms/ui' +import { useEffect, useState } from 'react' + +import { ipalT } from '../admin-i18n/t.js' +import { faviconProblems } from './faviconProblems.js' + +export type FaviconCheckProps = { + /** Upload field holding the icon. Default: the field this sits under, else 'favicon'. */ + fieldPath?: string + /** Upload collection of the icon. Default 'media'. */ + mediaSlug?: string + /** Set by Payload for a field component. */ + path?: string +} + +const id = (value: unknown) => + typeof value === 'object' && value !== null ? (value as { id?: number | string }).id : (value as number | string | undefined) + +/** + * Hint under the site icon in Site settings: Google shows a favicon only when it + * is at least 48×48 px, and a non-square one gets cropped. Reads the chosen + * image's size and warns; saving is never blocked. SVG icons pass. + */ +export function FaviconCheck({ fieldPath, mediaSlug = 'media', path }: FaviconCheckProps) { + const value = useFormFields(([f]) => f[fieldPath ?? path ?? 'favicon']?.value) + const mediaId = id(value) + const { + config: { + routes: { api }, + serverURL, + }, + } = useConfig() + const { t } = useTranslation() + const [problems, setProblems] = useState([]) + + useEffect(() => { + if (mediaId === undefined || mediaId === null || mediaId === '') { + setProblems([]) + return + } + const controller = new AbortController() + void (async () => { + try { + const res = await fetch(`${serverURL ?? ''}${api}/${mediaSlug}/${encodeURIComponent(String(mediaId))}?depth=0`, { + credentials: 'include', + signal: controller.signal, + }) + const media = res.ok ? ((await res.json()) as { height?: number; mimeType?: string; width?: number }) : null + const found = media ? faviconProblems(media) : [] + setProblems(found.map((p) => ipalT(t, p.key, { height: p.height, width: p.width }))) + } catch { + // aborted or offline — a hint is not worth an error + } + })() + return () => controller.abort() + }, [api, mediaId, mediaSlug, serverURL, t]) + + if (!problems.length) {return null} + + return ( +
+ {problems.map((text) => ( +

{text}

+ ))} +
+ ) +} diff --git a/src/modules/seo/faviconProblems.ts b/src/modules/seo/faviconProblems.ts new file mode 100644 index 0000000..2b16e41 --- /dev/null +++ b/src/modules/seo/faviconProblems.ts @@ -0,0 +1,17 @@ +/** Smallest favicon Google shows in search results. */ +export const FAVICON_MIN_SIZE = 48 + +export type FaviconProblem = { height: number; key: 'faviconNotSquare' | 'faviconTooSmall'; width: number } + +/** + * What is wrong with a favicon for Google: under 48×48 px, or not square. + * SVG scales, and an image without known dimensions is not judged. + */ +export function faviconProblems(media: { height?: null | number; mimeType?: null | string; width?: null | number }): FaviconProblem[] { + const { height, mimeType, width } = media + if (mimeType === 'image/svg+xml' || typeof width !== 'number' || typeof height !== 'number') {return []} + const out: FaviconProblem[] = [] + if (width < FAVICON_MIN_SIZE || height < FAVICON_MIN_SIZE) {out.push({ height, key: 'faviconTooSmall', width })} + if (width !== height) {out.push({ height, key: 'faviconNotSquare', width })} + return out +} diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index 96bccf4..a963e5a 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -28,6 +28,8 @@ export { composeTitle } from './composeTitle.js' export type { TitleOrder } from './composeTitle.js' export { createMetadataGenerator } from './createMetadataGenerator.js' export { createPageMetadata } from './createPageMetadata.js' +export { FAVICON_MIN_SIZE, faviconProblems } from './faviconProblems.js' +export type { FaviconProblem } from './faviconProblems.js' export { formatOpeningHours } from './formatOpeningHours.js' export { buildHreflangAlternates } from './hreflang.js' export { diff --git a/src/modules/seo/validateFavicon.ts b/src/modules/seo/validateFavicon.ts index ba0097d..f6efb69 100644 --- a/src/modules/seo/validateFavicon.ts +++ b/src/modules/seo/validateFavicon.ts @@ -1,14 +1,14 @@ import type { FieldHook } from 'payload' +import { faviconProblems } from './faviconProblems.js' + /** - * Field validation for the favicon upload: Google rejects favicons under 48×48, - * so warn the editor at save time if the uploaded icon is too small or not - * square. This ENFORCES the requirement instead of silently shipping a favicon - * Google won't display. + * Server-side check of the favicon upload: Google rejects favicons under 48×48, + * and a non-square icon gets cropped. Logs a warning on save; it never blocks + * the save. Editors see the same check under the field (`FaviconCheck`, /admin). * - * Attach to the favicon field's validate (or as a beforeValidate hook on the - * Media relationship). Non-blocking by default — returns a warning string that - * Payload surfaces; make it throw if you want a hard block. + * Attach as a beforeValidate hook on your own favicon field; the plugin wires it + * on Site settings itself. * * Note: dimensions come from the related Media doc (Payload stores width/height * for image uploads), so this checks the resolved upload, not the raw file. @@ -23,26 +23,12 @@ export const validateFaviconField: FieldHook = async ({ req, value }) => { depth: 0, }) - const width = (media as { width?: number }).width - const height = (media as { height?: number }).height - const mimeType = (media as { mimeType?: string }).mimeType - - // SVG scales infinitely — skip size checks. - if (mimeType === 'image/svg+xml') {return value} - - if (typeof width === 'number' && typeof height === 'number') { - if (width < 48 || height < 48) { - req.payload.logger.warn( - `[ipal] Favicon is ${width}×${height}px. Google requires ≥48×48 to ` + - `display it in search results. Upload a larger square icon (96 or 192px).`, - ) - } - if (width !== height) { - req.payload.logger.warn( - `[ipal] Favicon is not square (${width}×${height}). Use a square icon ` + - `so it isn't cropped in the browser tab or search results.`, - ) - } + for (const { height, key, width } of faviconProblems(media as { height?: number; mimeType?: string; width?: number })) { + req.payload.logger.warn( + key === 'faviconTooSmall' + ? `[ipal] Favicon is ${width}×${height}px. Google requires ≥48×48 to display it in search results. Upload a larger square icon (96 or 192px).` + : `[ipal] Favicon is not square (${width}×${height}). Use a square icon so it isn't cropped in the browser tab or search results.`, + ) } } catch { // Media lookup failed — don't block the save over a validation warning. diff --git a/src/modules/stats/admin/StatsView.tsx b/src/modules/stats/admin/StatsView.tsx index b1339b1..1b21c3d 100644 --- a/src/modules/stats/admin/StatsView.tsx +++ b/src/modules/stats/admin/StatsView.tsx @@ -5,7 +5,8 @@ import { Gutter } from '@payloadcms/ui' import type { StatsVisit } from '../collection.js' -import { formatDateTime } from '../../admin-i18n/t.js' +import { DocumentTitle } from '../../admin-i18n/DocumentTitle.js' +import { adminDocumentTitle, formatDateTime } from '../../admin-i18n/t.js' import { VISITOR_ID_PATTERN } from '../parse.js' import { canReadStats } from './canReadStats.js' import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js' @@ -174,6 +175,8 @@ export async function StatsView(props: Props) {
+ {/* meta.title in the view config is plain English text; this puts the tab title in the admin language */} + {content}
diff --git a/test/adminUxFollowUps.test.ts b/test/adminUxFollowUps.test.ts new file mode 100644 index 0000000..b967a1f --- /dev/null +++ b/test/adminUxFollowUps.test.ts @@ -0,0 +1,115 @@ +import type { BasePayload, Config, Field, GlobalConfig, PayloadRequest } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import { adminDocumentTitle, adminTexts, ipalT } from '../src/modules/admin-i18n/index.js' +import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js' +import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from '../src/modules/consent/scanner/integrations.js' +import { collectCookieFindings } from '../src/modules/consent/scanner/scan.js' +import { constructionCloseLabel } from '../src/modules/construction/texts.js' +import { faviconProblems } from '../src/modules/seo/faviconProblems.js' +import { ipalKit } from '../src/plugin.js' + +vi.mock('server-only', () => ({})) + +/** Payload's `t` over the plugin texts, for one language. */ +const tFor = (lang: 'en' | 'pl') => + ((key: string, vars?: Record) => + ((adminTexts[lang] as Record)[key.replace(/^ipal:/, '')] ?? key).replace(/\{\{(\w+)\}\}/g, (_, n: string) => + String((vars?.[n] as number | string | undefined) ?? ''), + )) as never + +const fakePayload = (integrations: Record = {}) => + ({ + config: { cookiePrefix: 'payload' }, + findGlobal: vi.fn(async () => integrations), + logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() }, + }) as unknown as BasePayload + +describe('statistics page title', () => { + test('tab title in the admin language, with the title suffix', () => { + expect(adminDocumentTitle(ipalT(tFor('pl'), 'statsTitle'), '- Payload')).toBe('Statystyki - Payload') + expect(adminDocumentTitle(ipalT(tFor('en'), 'statsTitle'), '- Acme')).toBe('Statistics - Acme') + expect(adminDocumentTitle('Statystyki', '')).toBe('Statystyki') + }) +}) + +describe('cookie scanner integration names', () => { + test('built-in names come from the shared admin texts, in English and Polish', () => { + const admin = DEFAULT_COOKIE_INTEGRATIONS.find((i) => i.key === 'admin')! + expect(admin.label).toEqual({ en: adminTexts.en.cookieIntegrationAdmin, pl: adminTexts.pl.cookieIntegrationAdmin }) + expect(integrationLabel(admin, 'pl')).toBe('Logowanie do panelu') + expect(integrationLabel(admin, 'en')).toBe('Admin panel login') + // a language without its own text falls back to English + expect(integrationLabel(admin, 'de')).toBe('Admin panel login') + // product names stay one string for every language + expect(integrationLabel(DEFAULT_COOKIE_INTEGRATIONS.find((i) => i.key === 'ga4')!, 'pl')).toBe('Google Analytics 4') + // a project's own integration may still use a plain string + expect(integrationLabel({ label: 'Chat' }, 'pl')).toBe('Chat') + }) + + test('the scan endpoint answers in the admin language of the request', async () => { + const [get] = buildCookieScanEndpoints({ access: () => true }, { localeCount: 2, stats: true }) + const ask = async (language: string) => { + const req = { i18n: { language }, payload: fakePayload() } as unknown as PayloadRequest + return ((await (await get.handler(req)).json()) as { integrations: { key: string; label: string }[] }).integrations + } + expect(await ask('pl')).toEqual([ + { key: 'consent', label: 'Baner cookies' }, + { key: 'admin', label: 'Logowanie do panelu' }, + { key: 'locale', label: 'Wybór języka' }, + { key: 'stats', label: 'Wbudowane statystyki' }, + ]) + expect((await ask('en')).map((i) => i.label)).toEqual(['Cookie banner', 'Admin panel login', 'Language choice', 'Built-in statistics']) + }) + + test("source names stored by a scan follow the scanning editor's language", async () => { + const ctx = { integrations: {}, language: 'pl', payload: fakePayload(), plugin: { localeCount: 1, stats: true } } + const declarations = [{ name: 'chat', category: 'functional' as const, purpose: 'Chat', retention: '1 day', setBeforeConsent: false, vendor: 'Chat' }] + const { findings } = await collectCookieFindings({ ctx, database: false, declarations }) + expect(findings.find((f) => f.name === 'chat')?.sourceDetail).toBe('Projekt') + expect(findings.find((f) => f.name === 'ipal_vid')?.sourceDetail).toBe('Wbudowane statystyki') + }) +}) + +describe('maintenance notice close button', () => { + test('screen-reader name in the page language', () => { + expect(constructionCloseLabel('pl')).toBe('Zamknij') + expect(constructionCloseLabel('pl-PL')).toBe('Zamknij') + expect(constructionCloseLabel('en')).toBe('Close') + expect(constructionCloseLabel('de')).toBe('Close') + expect(constructionCloseLabel()).toBe('Close') + }) +}) + +describe('favicon check', () => { + test('too small, not square, or fine; SVG and unknown sizes pass', () => { + expect(faviconProblems({ height: 32, mimeType: 'image/png', width: 32 })).toEqual([{ height: 32, key: 'faviconTooSmall', width: 32 }]) + expect(faviconProblems({ height: 96, mimeType: 'image/png', width: 192 })).toEqual([{ height: 96, key: 'faviconNotSquare', width: 192 }]) + expect(faviconProblems({ height: 40, width: 30 }).map((p) => p.key)).toEqual(['faviconTooSmall', 'faviconNotSquare']) + expect(faviconProblems({ height: 192, mimeType: 'image/png', width: 192 })).toEqual([]) + expect(faviconProblems({ height: 16, mimeType: 'image/svg+xml', width: 16 })).toEqual([]) + expect(faviconProblems({ mimeType: 'image/png' })).toEqual([]) + }) + + test('warnings read in both admin languages with the size filled in', () => { + expect(ipalT(tFor('en'), 'faviconTooSmall', { height: 32, width: 32 })).toContain('32×32 px') + expect(ipalT(tFor('pl'), 'faviconTooSmall', { height: 32, width: 32 })).toBe('Ikona ma 32×32 px. Google pokazuje ikony od 48×48 px; wgraj większą.') + expect(ipalT(tFor('pl'), 'faviconNotSquare', { height: 96, width: 192 })).toContain('192×96 px') + }) + + test('Site settings shows the check under the site icon', async () => { + const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'media', fields: [], upload: true }, + ], + secret: 'test', + } as unknown as Config) + const settings = config.globals!.find((g) => g.slug === 'site-settings') as GlobalConfig + const general = (settings.fields[0] as { tabs: { fields: Field[] }[] }).tabs[0].fields + const favicon = general.find((f) => 'name' in f && f.name === 'favicon') as { admin: { components: { afterInput: unknown[] } } } + expect(favicon.admin.components.afterInput).toEqual(['@intecion/ipal-kit/admin#FaviconCheck']) + }) +}) diff --git a/test/construction.test.ts b/test/construction.test.ts index 950ebbd..98e9d79 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -86,7 +86,7 @@ describe('under construction — Site Settings → createPageRoute', () => { }) const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) const mode = await helpers.getConstructionMode('pl') - expect(mode).toMatchObject({ enabled: true, homePath: '/pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } }) + expect(mode).toMatchObject({ enabled: true, homePath: '/pl', locale: 'pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } }) expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief'])) await expect(open('pl')).resolves.toBeTruthy()