Cookies: fill empty languages, and one Cookies entry in the admin

Every language filled (fillEmptyLocales, default on): text saved in one
language goes to every language where the same field is still empty, never
over a language's own text. Applies to the cookie list (purpose, duration)
and the cookie review (purpose, duration). Scanner and approval writes give
a language without its own text the default language's text. Building
blocks: buildFillEmptyLocalesGlobalHook / CollectionHook, fillEmptyLocales,
withFillLocales.

One Cookies entry (cookieScanner.adminLayout, default combined): the
Cookie banner global is now labelled Cookies and gets Review and approve
(scan box and approval list inline) and Site check tabs, built from ui
fields. Cookie review and Cookie check leave the navigation
(admin.group false) but keep their pages, data and API. This is
presentation only: no schema change and no migration, only
generate:importmap. adminLayout separate keeps the old layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-28 22:55:11 +01:00
co-authored by Claude Opus 5.5
parent a9e1adc03b
commit b10c2dc0e3
34 changed files with 812 additions and 96 deletions
@@ -37,14 +37,20 @@ const CSS = `
*/
export function CookieApprovalForm({
adminRoute = '/admin',
blockedReason,
gone,
labels = COOKIE_SCAN_LABELS,
onApproved,
pending,
unknownCategory,
}: {
adminRoute?: string
/** Why approving is not possible right now (shown next to the disabled button), e.g. unsaved changes. */
blockedReason?: null | string
gone: CookieApprovalItem[]
labels?: Record<string, CookieScanLabels>
/** After a successful approval. Default: reload the route's server data. */
onApproved?: (result: CookieApprovalResult) => void
pending: CookieApprovalItem[]
unknownCategory: ConsentCategory
}) {
@@ -81,7 +87,8 @@ export function CookieApprovalForm({
setDone(data.result)
toast.success(fill(t.approvalDone, { ...data.result }))
setExcluded(new Set())
router.refresh()
if (onApproved) {onApproved(data.result)}
else {router.refresh()}
} catch {
toast.error(t.approvalError)
} finally {
@@ -158,10 +165,11 @@ export function CookieApprovalForm({
</section>
))}
<div className="ipal-bar">
<Button buttonStyle="primary" disabled={busy || !selected.length} margin={false} onClick={() => void approve()} size="large">
<Button buttonStyle="primary" disabled={busy || !selected.length || Boolean(blockedReason)} margin={false} onClick={() => void approve()} size="large">
{busy ? t.approving : `${t.approvalButton} (${selected.length})`}
</Button>
<span>{fill(t.approvalSelected, { count: selected.length })} / {pending.length}</span>
{blockedReason ? <span role="status">{blockedReason}</span> : null}
</div>
</>
) : (
@@ -0,0 +1,78 @@
'use client'
import { useConfig, useFormModified, useLocale, useTranslation } from '@payloadcms/ui'
import { useCallback, useEffect, useState } from 'react'
import type { ConsentCategory } from '../categories.js'
import type { CookieApprovalList } from './approval.js'
import type { CookieScanLabels } from './labels.js'
import { CookieApprovalForm } from './CookieApprovalForm.js'
import { CookieScanButton } from './CookieScanButton.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
/**
* "Review and approve" tab of the Cookies global (`ui` field, combined admin
* layout): the scan box, the approval list inline, and a link to the review
* entries one by one. Approving writes the cookie list on this same screen, so
* the page reloads afterwards — and approving waits while the form has
* unsaved changes, which a reload would lose.
*/
export function CookieReviewTab({
approval = true,
labels = COOKIE_SCAN_LABELS,
unknownCategory = 'marketing',
}: {
approval?: boolean
labels?: Record<string, CookieScanLabels>
unknownCategory?: ConsentCategory
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
const { code: locale } = useLocale()
const modified = useFormModified()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const admin = (config.routes?.admin ?? '/admin').replace(/\/$/, '')
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-approval?locale=${encodeURIComponent(locale ?? '')}`
const [list, setList] = useState<CookieApprovalList | null>(null)
const [reloading, setReloading] = useState(false)
const load = useCallback(() => {
if (!approval) {return}
fetch(endpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: CookieApprovalList | null) => setList(data ? { gone: data.gone ?? [], pending: data.pending ?? [] } : { gone: [], pending: [] }))
.catch(() => setList({ gone: [], pending: [] }))
}, [approval, endpoint])
useEffect(load, [load])
return (
<div data-ipal="cookies-review-tab" style={{ marginTop: '1rem' }}>
<CookieScanButton approval={false} labels={labels} onChange={load} />
{approval ? (
list ? (
<CookieApprovalForm
adminRoute={admin}
blockedReason={reloading ? t.reloading : modified ? t.saveFirst : null}
gone={list.gone}
labels={labels}
onApproved={() => {
// The cookie list in this form is now out of date: load the saved one.
setReloading(true)
setTimeout(() => window.location.reload(), 1200)
}}
pending={list.pending}
unknownCategory={unknownCategory}
/>
) : (
<p>{t.loadingList}</p>
)
) : null}
<p style={{ marginTop: '1.5rem' }}>
<a href={`${admin}/collections/cookie-review`}>{t.openReviewList}</a>
</p>
</div>
)
}
export default CookieReviewTab
@@ -41,11 +41,17 @@ export function CookieScanButton({
approval = false,
crawl = false,
labels = COOKIE_SCAN_LABELS,
onChange,
scan: showScan = true,
}: {
/** Cookie approval is on: show how many cookies wait and link to the approval view. */
approval?: boolean
crawl?: boolean
labels?: Record<string, CookieScanLabels>
/** Called after a scan or a finished site check (the Cookies tabs reload their lists). */
onChange?: () => void
/** Show the "Scan cookies" part. Default true; the Site check tab shows only the crawl. */
scan?: boolean
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
@@ -84,6 +90,7 @@ export function CookieScanButton({
if (wasRunning && data.status !== 'running') {
router.refresh()
refreshPending()
onChange?.()
}
wasRunning = data.status === 'running'
} catch {
@@ -96,7 +103,7 @@ export function CookieScanButton({
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, refreshPending, router])
}, [crawl, crawlEndpoint, onChange, refreshPending, router])
const startCrawl = async () => {
setCrawlStarting(true)
@@ -130,6 +137,7 @@ export function CookieScanButton({
setStatus({ kind: 'done', summary: data.summary })
router.refresh()
refreshPending()
onChange?.()
} catch {
setStatus({ kind: 'error' })
}
@@ -140,42 +148,46 @@ export function CookieScanButton({
return (
<div className="ipal-cookie-scan" data-ipal="cookie-scan" style={{ marginBottom: '1.5rem' }}>
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
{integrations ? (
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
</p>
) : null}
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
<textarea
aria-label={t.namesLabel}
id="ipal-cookie-scan-names"
onChange={(e) => setNames(e.target.value)}
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
rows={3}
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
value={names}
/>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</Button>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{approval && pending ? (
<span data-ipal="cookie-approval-pending">
<strong>{fill(t.approvalPending, { count: pending })}</strong>{' '}
<Button buttonStyle="primary" el="anchor" margin={false} size="medium" url={approvalView}>
{t.approvalLink}
{showScan ? (
<>
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
{integrations ? (
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
</p>
) : null}
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
<textarea
aria-label={t.namesLabel}
id="ipal-cookie-scan-names"
onChange={(e) => setNames(e.target.value)}
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
rows={3}
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
value={names}
/>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</Button>
</span>
) : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{approval && pending ? (
<span data-ipal="cookie-approval-pending">
<strong>{fill(t.approvalPending, { count: pending })}</strong>{' '}
<Button buttonStyle="primary" el="anchor" margin={false} size="medium" url={approvalView}>
{t.approvalLink}
</Button>
</span>
) : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
</>
) : null}
{crawl ? (
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
<div data-ipal="cookie-crawl" style={showScan ? { borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' } : {}}>
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button
@@ -0,0 +1,70 @@
'use client'
import { useConfig, useTranslation } from '@payloadcms/ui'
import { useCallback, useEffect, useState } from 'react'
import type { CrawlViolation } from './crawl/violations.js'
import type { CookieScanLabels } from './labels.js'
import { CookieScanButton } from './CookieScanButton.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
/**
* "Site check" tab of the Cookies global (`ui` field, combined admin layout,
* only with `cookieScanner.crawl`): start a check, its status, the violations
* of the latest check, and a link to the warning e-mail settings.
*/
export function CookieSiteCheckTab({ labels = COOKIE_SCAN_LABELS }: { labels?: Record<string, CookieScanLabels> }) {
const { i18n } = useTranslation()
const { config } = useConfig()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const admin = (config.routes?.admin ?? '/admin').replace(/\/$/, '')
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/globals/cookie-crawl?depth=0`
const [violations, setViolations] = useState<CrawlViolation[] | null>(null)
const load = useCallback(() => {
fetch(endpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: { violations?: CrawlViolation[] | null } | null) => setViolations(Array.isArray(data?.violations) ? data.violations : []))
.catch(() => setViolations([]))
}, [endpoint])
useEffect(load, [load])
const kind = (v: CrawlViolation) => (v.kind === 'request' ? t.request : v.kind === 'cookie' ? t.cookie : v.kind === 'localStorage' ? t.localStorage : t.sessionStorage)
return (
<div data-ipal="cookies-site-check-tab" style={{ marginTop: '1rem' }}>
<CookieScanButton crawl labels={labels} onChange={load} scan={false} />
<h3 style={{ marginTop: '1.5rem' }}>{t.violationsTitle}</h3>
{violations === null ? <p>{t.loadingList}</p> : null}
{violations?.length === 0 ? <p>{t.noViolations}</p> : null}
{violations?.length ? (
<table style={{ borderCollapse: 'collapse', width: '100%' }}>
<thead>
<tr>
<th scope="col" style={{ textAlign: 'left' }}>{t.name}</th>
<th scope="col" style={{ textAlign: 'left' }}>{t.kind}</th>
<th scope="col" style={{ textAlign: 'left' }}>{t.category}</th>
<th scope="col" style={{ textAlign: 'left' }}>{t.pages}</th>
</tr>
</thead>
<tbody>
{violations.map((v) => (
<tr key={`${v.kind}:${v.name}`}>
<td><code>{v.name}</code></td>
<td>{kind(v)}</td>
<td>{v.category && v.category in t ? t[v.category as keyof CookieScanLabels] : (v.category ?? '')}</td>
<td>{v.pages.join(', ')}</td>
</tr>
))}
</tbody>
</table>
) : null}
<p style={{ marginTop: '1.5rem' }}>
<a href={`${admin}/globals/cookie-crawl`}>{t.warningEmailsLink}</a>
</p>
</div>
)
}
export default CookieSiteCheckTab
+63
View File
@@ -0,0 +1,63 @@
import type { Field, GlobalConfig, Tab } from 'payload'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
import { labelRecord } from './labels.js'
/**
* The combined admin layout (`cookieScanner.adminLayout: 'combined'`, the
* default): the Cookies global gets a "Review and approve" tab and — with the
* crawl — a "Site check" tab. They are `ui` fields (no data, no schema
* change) that render the scanner's admin components; the review list and the
* site-check global leave the navigation but keep their pages and API.
*/
export function addCookieScannerTabs(
global: GlobalConfig,
{
approval,
crawl,
labels,
unknownCategory,
}: { approval: boolean; crawl: boolean; labels: Record<string, CookieScanLabels>; unknownCategory?: ConsentCategory },
): GlobalConfig {
const tabsField = global.fields.find((f): f is { tabs: Tab[] } & Field => f.type === 'tabs')
if (!tabsField) {return global} // a project replaced the global's fields — nothing to attach to
const tabs: Tab[] = [
{
fields: [
{
name: 'ipalCookieReview',
type: 'ui',
admin: {
components: {
Field: {
clientProps: { approval, labels, ...(unknownCategory ? { unknownCategory } : {}) },
path: '@intecion/ipal-kit/admin#CookieReviewTab',
},
},
},
},
],
label: labelRecord(labels, 'tabReview'),
},
...(crawl
? [
{
fields: [
{
name: 'ipalCookieSiteCheck',
type: 'ui' as const,
admin: { components: { Field: { clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieSiteCheckTab' } } },
},
],
label: labelRecord(labels, 'tabSiteCheck'),
},
]
: []),
]
return {
...global,
fields: global.fields.map((f) => (f === tabsField ? { ...tabsField, tabs: [...tabsField.tabs, ...tabs] } : f)),
}
}
+2 -2
View File
@@ -14,7 +14,7 @@ import { addToCookieList } from './sync.js'
/**
* One approval for everything a scan or crawl found: the "Approve cookies" view
* lists what is waiting, grouped by consent category, and one button adds the
* ticked cookies to Cookie banner → Cookies — which feeds the cookie banner's
* ticked cookies to Cookies → Cookies — which feeds the cookie banner's
* detailed window and the cookie policy table. Nothing is added before that.
*/
export const COOKIE_APPROVAL_PATH = '/ipal/cookie-approval'
@@ -102,7 +102,7 @@ export async function countPendingCookies(payload: BasePayload): Promise<number>
/**
* Approves pending entries (all of them, or only `ids`): each becomes accepted
* and goes to Cookie banner → Cookies in every locale — a missing row is added,
* and goes to Cookies → Cookies in every locale — a missing row is added,
* an existing one (same name or pattern) only gets its empty text filled, its
* category is kept. A cookie without a category gets `unknownCategory` (needs
* consent) and every cookie without a purpose is flagged "Needs description".
+1
View File
@@ -1,4 +1,5 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
export { addCookieScannerTabs } from './adminTabs.js'
export {
approveCookies,
buildCookieApprovalEndpoints,
+36
View File
@@ -67,9 +67,11 @@ export type CookieScanLabels = {
integration: string
integrationsFound: string
integrationsNone: string
kind: string
lastScannedAt: string
listed: string
listedDescription: string
loadingList: string
localStorage: string
manual: string
markerChanged: string
@@ -85,12 +87,18 @@ export type CookieScanLabels = {
notifyEmails: string
notifyEmailsDescription: string
notifyEmailsInvalid: string
noViolations: string
openCookieBanner: string
openReviewList: string
pages: string
plural: string
project: string
purpose: string
rejected: string
reloading: string
request: string
retention: string
saveFirst: string
scanButton: string
scanError: string
scanIntro: string
@@ -109,6 +117,8 @@ export type CookieScanLabels = {
status: string
statusDescription: string
storage: string
tabReview: string
tabSiteCheck: string
uncategorized: string
uncategorizedNote: string
unknown: string
@@ -116,6 +126,8 @@ export type CookieScanLabels = {
violation: string
violationDescription: string
violationDetail: string
violationsTitle: string
warningEmailsLink: string
}
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
@@ -184,9 +196,11 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
integration: 'Built-in integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration that uses cookies is on.',
kind: 'Type',
lastScannedAt: 'Last found',
listed: 'In cookie list',
listedDescription: 'Already in the cookie list of the cookie banner.',
loadingList: 'Loading…',
localStorage: 'Local storage',
manual: 'Added by hand',
markerChanged: 'Changed',
@@ -201,12 +215,18 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
notifyEmails: 'Warning e-mails to',
notifyEmailsDescription: 'Comma-separated addresses that get a warning when a check finds problems; leave empty for none.',
notifyEmailsInvalid: 'Enter e-mail addresses separated by commas, e.g. [email protected], [email protected].',
noViolations: 'No violations in the latest check.',
openCookieBanner: 'Open cookie banner',
openReviewList: 'Edit cookies one by one',
pages: 'Pages',
plural: 'Cookie review',
project: 'Site configuration',
purpose: 'Purpose',
rejected: 'Rejected',
reloading: 'Added. Reloading the cookie list…',
request: 'Request',
retention: 'Duration',
saveFirst: 'Save your changes first.',
scanButton: 'Scan cookies',
scanError: 'The scan failed. Please try again.',
scanIntro: 'Finds the cookies of the integrations in use; nothing is added to the cookie banner until you approve.',
@@ -224,6 +244,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
status: 'Status',
statusDescription: 'Accepted cookies are added to the cookie list; rejecting never removes them from it.',
storage: 'Stored in',
tabReview: 'Review and approve',
tabSiteCheck: 'Site check',
uncategorized: 'Not yet described',
uncategorizedNote: 'Nothing is known about these yet; they are added as {category} until you describe them.',
unknown: 'Unknown',
@@ -231,6 +253,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
violation: 'Violation',
violationDescription: 'Not necessary, yet seen before consent in the latest site check.',
violationDetail: 'Violation details',
violationsTitle: 'Violations in the latest check',
warningEmailsLink: 'Warning e-mails',
},
pl: {
name: 'Nazwa',
@@ -297,9 +321,11 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
integration: 'Wbudowana integracja',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja używająca cookies nie jest włączona.',
kind: 'Rodzaj',
lastScannedAt: 'Ostatnio znaleziony',
listed: 'Na liście cookies',
listedDescription: 'Już jest na liście cookies banera.',
loadingList: 'Wczytywanie…',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
markerChanged: 'Zmieniony',
@@ -314,12 +340,18 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku, na które trafi ostrzeżenie, gdy kontrola wykryje problemy; zostaw puste, aby nie wysyłać.',
notifyEmailsInvalid: 'Wpisz adresy e-mail oddzielone przecinkami, np. [email protected], [email protected].',
noViolations: 'Brak naruszeń w ostatniej kontroli.',
openCookieBanner: 'Otwórz baner cookies',
openReviewList: 'Edytuj cookies pojedynczo',
pages: 'Strony',
plural: 'Przegląd cookies',
project: 'Konfiguracja witryny',
purpose: 'Cel',
rejected: 'Odrzucony',
reloading: 'Dodano. Odświeżanie listy cookies…',
request: 'Zapytanie',
retention: 'Okres',
saveFirst: 'Najpierw zapisz zmiany.',
scanButton: 'Skanuj cookies',
scanError: 'Skanowanie nie powiodło się. Spróbuj ponownie.',
scanIntro: 'Wyszukuje cookies używanych integracji; nic nie trafi do banera cookies bez zatwierdzenia.',
@@ -337,6 +369,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
status: 'Status',
statusDescription: 'Zaakceptowane cookies trafiają na listę cookies; odrzucenie nigdy ich z niej nie usuwa.',
storage: 'Miejsce zapisu',
tabReview: 'Przegląd i zatwierdzanie',
tabSiteCheck: 'Kontrola witryny',
uncategorized: 'Jeszcze bez opisu',
uncategorizedNote: 'Nic o nich jeszcze nie wiadomo; zostaną dodane jako {category} do czasu uzupełnienia opisu.',
unknown: 'Nieznane',
@@ -344,6 +378,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
violation: 'Naruszenie',
violationDescription: 'Nie jest niezbędny, a pojawił się przed zgodą w ostatniej kontroli witryny.',
violationDetail: 'Szczegóły naruszenia',
violationsTitle: 'Naruszenia w ostatniej kontroli',
warningEmailsLink: 'Ostrzeżenia e-mail',
},
}
+4 -2
View File
@@ -21,11 +21,13 @@ export function textFor(text: LocalizedText | undefined, locale: string): string
return text[locale] ?? text.en ?? Object.values(text)[0]
}
/** What a scan suggests for an entry, resolved for the project's locales. */
/** What a scan suggests for an entry, resolved for the project's locales (default locale first). */
export function suggestionFor(finding: CookieFinding, locales: string[]): CookieReviewValues {
const perLocale = (text: LocalizedText | undefined) => {
if (text === undefined) {return undefined}
return Object.fromEntries(locales.map((l) => [l, textFor(text, l) ?? null]))
// A locale without its own text gets the default locale's (locales[0]), then English, then any.
const fallback = typeof text === 'string' ? text : (text[locales[0]] ?? undefined)
return Object.fromEntries(locales.map((l) => [l, (typeof text === 'string' ? text : text[l]) ?? fallback ?? textFor(text, l) ?? null]))
}
const out: CookieReviewValues = {}
if (finding.category) {out.category = finding.category}
+2 -1
View File
@@ -43,8 +43,9 @@ export async function addToCookieList({
const codes = l ? (l.localeCodes ?? []) : []
const defaultLocale = l ? l.defaultLocale : undefined
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
// A locale without its own text gets the default locale's text — never nothing.
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
(locale ? map?.[locale]?.trim() || (defaultLocale ? map?.[defaultLocale]?.trim() : '') : map && Object.values(map)[0]) || null
// fallbackLocale off for reads AND writes: an update in one locale otherwise reads the
// stored rows with the default locale's text filled in and saves that text into it.
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
+7
View File
@@ -97,6 +97,13 @@ export type CookieScanSummary = {
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan) and start a crawl. Default: `editor` and up. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* `'combined'` (default): one "Cookies" entry in the navigation — the review
* list and the site check become tabs of the Cookies global ("Review and
* approve", "Site check") and leave the navigation; their pages, data and API
* stay. `'separate'`: each keeps its own navigation entry.
*/
adminLayout?: 'combined' | 'separate'
/**
* One approval for everything a scan or crawl found: the "Approve cookies"
* view (grouped by category, one "Approve and add" button) and a dashboard
+134
View File
@@ -0,0 +1,134 @@
import type { BasePayload, CollectionAfterChangeHook, CollectionConfig, GlobalAfterChangeHook, GlobalConfig, PayloadRequest } from 'payload'
/**
* Localized text the editor wrote in one language goes to every language that
* is still empty — so a cookie added in Polish is not blank on the English page.
* A language that already has its own text is never touched: the editor can
* still change any language on its own.
*
* Fields: `'purpose'` (top-level) or `'cookies.purpose'` (a sub-field of the
* rows of an array; rows are matched by their id, which Payload keeps the same
* in every locale).
*
* Payload's own `localization.fallback` only covers part of this: an empty
* locale *reads* as the default locale's text, but nothing is stored, the admin
* shows the field empty, and the text always comes from the default locale,
* not from the language that was just edited.
*/
export type FillEmptyLocalesTarget = { collection: string; id: number | string } | { global: string }
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/** Writes `source`'s text (read in `sourceLocale`) into every other locale where that text is empty. Returns the locales changed. */
export async function fillEmptyLocales({
fields,
payload,
req,
source,
sourceLocale,
target,
}: {
fields: string[]
payload: BasePayload
req?: PayloadRequest
source: Record<string, unknown>
sourceLocale: string
target: FillEmptyLocalesTarget
}): Promise<string[]> {
const l = payload.config.localization
if (!l) {return []}
const others = l.localeCodes.filter((c) => c !== sourceLocale)
const common = { context: { ipalFillLocales: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
const changedLocales: string[] = []
for (const locale of others) {
const doc = (
'global' in target
? await payload.findGlobal({ ...common, slug: target.global as never, locale: locale as never })
: await payload.findByID({ ...common, id: target.id as never, collection: target.collection as never, locale: locale as never })
) as Record<string, unknown>
const patch: Record<string, unknown> = {}
for (const field of fields) {
const [head, sub] = field.split('.')
if (!sub) {
if (empty(doc[head]) && !empty(source[head])) {patch[head] = source[head]}
continue
}
const sourceRows = Array.isArray(source[head]) ? (source[head] as Record<string, unknown>[]) : []
const rows = (patch[head] as Record<string, unknown>[] | undefined) ?? (Array.isArray(doc[head]) ? (doc[head] as Record<string, unknown>[]).map((r) => ({ ...r })) : [])
let changed = false
for (const row of rows) {
const from = sourceRows.find((s) => s.id != null && s.id === row.id)
if (from && empty(row[sub]) && !empty(from[sub])) {
row[sub] = from[sub]
changed = true
}
}
if (changed) {patch[head] = rows}
}
if (!Object.keys(patch).length) {continue}
if ('global' in target) {
await payload.updateGlobal({ ...common, slug: target.global as never, data: patch as never, locale: locale as never })
} else {
await payload.update({ ...common, id: target.id as never, collection: target.collection as never, data: patch as never, locale: locale as never })
}
changedLocales.push(locale)
}
return changedLocales
}
/** Runs `fn` with `req`, then puts back req.locale / req.fallbackLocale (Local API calls with `req` change them). */
async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
const { fallbackLocale, locale } = req
try {
await fn()
} catch (err) {
req.payload.logger.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
}
}
/** Skips its own writes and writes that fill every locale themselves (the cookie scanner). */
const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*'
/**
* afterChange hook for a global: text saved in one language fills that field in
* every language where it is empty.
*
* hooks: { afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'cookie-settings', fields: ['cookies.purpose'] })] }
*/
export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: string[]; global: string }): GlobalAfterChangeHook {
return async ({ context, doc, req }) => {
if (skip(context, req.locale)) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { global } }),
)
return doc
}
}
/** The same for a collection: the saved document's text fills its empty languages. */
export function buildFillEmptyLocalesCollectionHook({ collection, fields }: { collection: string; fields: string[] }): CollectionAfterChangeHook {
return async ({ context, doc, req }) => {
if (skip(context, req.locale) || doc?.id == null) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { id: doc.id, collection } }),
)
return doc
}
}
/** Adds the fill hook to a global or a collection config (no fields = unchanged). */
export function withFillLocales<T extends CollectionConfig | GlobalConfig>(kind: 'collection' | 'global', entity: T, fields: string[] | undefined): T {
if (!fields?.length) {return entity}
const hook =
kind === 'collection'
? buildFillEmptyLocalesCollectionHook({ collection: entity.slug, fields })
: buildFillEmptyLocalesGlobalHook({ fields, global: entity.slug })
return { ...entity, hooks: { ...entity.hooks, afterChange: [...(entity.hooks?.afterChange ?? []), hook] } } as T
}
+2
View File
@@ -5,6 +5,8 @@ export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'
export { buildGlobalRevalidateHook, buildRevalidateHook } from './buildRevalidateHook.js'
export type { RevalidatePathFn } from './buildRevalidateHook.js'
export { buildFillEmptyLocalesCollectionHook, buildFillEmptyLocalesGlobalHook, fillEmptyLocales, withFillLocales } from './fillEmptyLocales.js'
export type { FillEmptyLocalesTarget } from './fillEmptyLocales.js'
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
export { setPublishedAtHook } from './setPublishedAt.js'