'use client' import { Button, useConfig, useTranslation } from '@payloadcms/ui' import { useRouter } from 'next/navigation.js' 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 = { configured: boolean error: null | string finishedAt: null | string missing: string[] startedAt: null | string status: 'done' | 'failed' | 'idle' | 'running' summary: { newUnknown?: null | number; pages?: null | number; violations?: null | number } | null } type Status = | { kind: 'done'; summary: CookieScanSummary } | { kind: 'error' } | { kind: 'idle' } | { kind: 'scanning' } const fill = (template: string, values: Record) => template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? '')) /** * Admin UI above the Cookie review list (beforeListTable): shows which * integrations a scan covers, takes optional extra cookie names, runs * POST /api/ipal/cookie-scan and reloads the list. With `crawl`, also "Crawl * site" (POST /api/ipal/cookie-crawl) and the latest crawl's status, polled * while it runs. Labels in the admin language (`labels` from the collection * config, English fallback). */ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record }) { const { i18n } = useTranslation() const { config } = useConfig() const router = useRouter() const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-scan` const [names, setNames] = useState('') const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null) const [status, setStatus] = useState({ kind: 'idle' }) const [crawlState, setCrawlState] = useState(null) const [crawlStarting, setCrawlStarting] = useState(false) const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl') const when = (iso: null | string) => (iso ? formatDateTime(iso, i18n.language) : '') useEffect(() => { if (!crawl) {return} let stopped = false let wasRunning = false const poll = async () => { try { const res = await fetch(crawlEndpoint, { credentials: 'include' }) const data = res.ok ? ((await res.json()) as CrawlState) : null if (stopped || !data) {return} setCrawlState(data) if (wasRunning && data.status !== 'running') {router.refresh()} wasRunning = data.status === 'running' } catch { // offline — try again on the next tick } } void poll() const timer = setInterval(() => void poll(), 3000) return () => { stopped = true clearInterval(timer) } }, [crawl, crawlEndpoint, router]) const startCrawl = async () => { setCrawlStarting(true) try { await fetch(crawlEndpoint, { credentials: 'include', method: 'POST' }) const res = await fetch(crawlEndpoint, { credentials: 'include' }) if (res.ok) {setCrawlState((await res.json()) as CrawlState)} } finally { setCrawlStarting(false) } } useEffect(() => { fetch(endpoint, { credentials: 'include' }) .then((r) => (r.ok ? r.json() : null)) .then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? [])) .catch(() => setIntegrations([])) }, [endpoint]) const scan = async () => { setStatus({ kind: 'scanning' }) try { const res = await fetch(endpoint, { body: JSON.stringify({ names: names.split('\n') }), credentials: 'include', headers: { 'Content-Type': 'application/json' }, method: 'POST', }) const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary } if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')} setStatus({ kind: 'done', summary: data.summary }) router.refresh() } catch { setStatus({ kind: 'error' }) } } const result = (s: CookieScanSummary) => t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? '')) return (

{t.scanIntro}

{integrations ? (

{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}

) : null}

{t.namesHint}