init commit for iPAL-kit plugin

This commit is contained in:
2026-07-18 20:30:23 +02:00
parent 10638127a9
commit 5733a9c8bf
119 changed files with 6892 additions and 411 deletions
+21
View File
@@ -0,0 +1,21 @@
'use client'
import { createContext, type ReactNode, use } from 'react'
import type { ConsentTexts } from './texts.js'
import { useConsent } from './useConsent.js'
type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsent>
const ConsentContext = createContext<ConsentContextValue | null>(null)
export function ConsentProvider({ children, texts }: { children: ReactNode; texts: ConsentTexts }) {
const consent = useConsent()
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
}
export function useConsentContext(): ConsentContextValue {
const ctx = use(ConsentContext)
if (!ctx) {throw new Error('useConsentContext must be used within ConsentProvider')}
return ctx
}
+147
View File
@@ -0,0 +1,147 @@
'use client'
import { Cookie } from 'lucide-react'
import { useEffect, useState } from 'react'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
/**
* Optional class overrides — for when tokens aren't enough, e.g. turning the
* bottom bar into a centred modal. Replaces the slot's classes outright.
*/
export type CookieBannerClassNames = {
primaryButton?: string
root?: string
secondaryButton?: string
}
/**
* Colours and radius come from CSS custom properties with built-in fallbacks,
* so the banner looks right with no setup, and re-skinning per client means
* declaring a few variables — no imports, no props, no specificity fights:
*
* ```css
* :root {
* --ipal-primary: #16a34a;
* --ipal-radius: 1rem;
* }
* ```
*
* Available: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,
* --ipal-text-muted, --ipal-primary, --ipal-primary-hover, --ipal-primary-text,
* --ipal-hover, --ipal-radius. Each has a `-dark` counterpart used under
* Tailwind's `dark:` variant (e.g. --ipal-surface-dark).
*
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
* exposing them as tokens would mean re-inventing CSS one variable at a time.
*/
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
const accent = 'text-[var(--ipal-primary,#2563eb)]'
const defaults = {
primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
}
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
const strongText =
'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
useEffect(() => {
setChoices(state)
}, [state])
if (decided) {return null}
const toggle = (cat: ConsentCategory) => {
if (cat === 'necessary') {return}
setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))
}
const rootClass = classNames?.root ?? defaults.root
const primaryClass = classNames?.primaryButton ?? defaults.primaryButton
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton
return (
<div aria-label="Cookie consent" className={rootClass} data-ipal="banner" role="dialog">
<div className="mx-auto max-w-4xl">
{!showSettings ? (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-start gap-3">
<Cookie aria-hidden="true" className={`h-6 w-6 shrink-0 ${accent}`} />
<p className={`text-justify text-sm ${bodyText}`}>
{texts.message}
{texts.privacyLink && (
<>
{' '}
<a
className={`${accent} underline hover:no-underline`}
href={texts.privacyLink.href}
>
{texts.privacyLink.label}
</a>
</>
)}
</p>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} onClick={() => setShowSettings(true)}>
{texts.buttons.settings}
</button>
<button className={secondaryClass} onClick={rejectAll}>
{texts.buttons.reject}
</button>
<button className={primaryClass} onClick={acceptAll}>
{texts.buttons.acceptAll}
</button>
</div>
</div>
) : (
<div className="flex flex-col gap-4">
<h2 className={`flex items-center gap-2 text-base font-semibold ${strongText}`}>
<Cookie aria-hidden="true" className={`h-5 w-5 ${accent}`} />
{texts.settingsTitle}
</h2>
<ul className="flex flex-col gap-3">
{CONSENT_CATEGORIES.map((cat) => (
<li className="flex items-start justify-between gap-4" key={cat}>
<div>
<p className={`text-sm font-medium ${strongText}`}>
{texts.categories[cat].title}
</p>
<p className={`text-xs ${mutedText}`}>{texts.categories[cat].description}</p>
</div>
<input
checked={cat === 'necessary' ? true : choices[cat]}
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
disabled={cat === 'necessary'}
onChange={() => toggle(cat)}
type="checkbox"
/>
</li>
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} onClick={() => setShowSettings(false)}>
{texts.buttons.back}
</button>
<button className={primaryClass} onClick={() => savePreferences(choices)}>
{texts.buttons.save}
</button>
</div>
</div>
)}
</div>
</div>
)
}
+35
View File
@@ -0,0 +1,35 @@
'use client'
import { Cookie } from 'lucide-react'
import { useConsentContext } from './ConsentContext.js'
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
* Hidden while the banner is showing.
*
* Colours follow the same CSS custom properties as CookieBanner
* (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's
* palette applies to both without touching either component. Pass className to
* replace the styling outright.
*/
export function CookieButton({ className }: { className?: string } = {}) {
const { decided, reopen } = useConsentContext()
if (!decided) {return null}
const cls =
className ??
'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +
'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +
'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'
return (
<button aria-label="Cookie settings" className={cls} data-ipal="cookie-button" onClick={reopen}>
<Cookie
aria-hidden="true"
className="h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]"
/>
</button>
)
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Cookie consent categories (GDPR). 'necessary' is always granted and cannot be
* disabled. The rest default to false until the user opts in.
*/
export const CONSENT_CATEGORIES = ['necessary', 'functional', 'analytics', 'marketing'] as const
export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number]
export type ConsentState = Record<ConsentCategory, boolean>
export const DEFAULT_CONSENT: ConsentState = {
necessary: true,
functional: false,
analytics: false,
marketing: false,
}
export const ACCEPT_ALL_CONSENT: ConsentState = {
necessary: true,
functional: true,
analytics: true,
marketing: true,
}
export const REJECT_ALL_CONSENT: ConsentState = { ...DEFAULT_CONSENT }
+7
View File
@@ -0,0 +1,7 @@
'use client'
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components.
export { useConsent } from './useConsent.js'
+99
View File
@@ -0,0 +1,99 @@
import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import type { ConsentTexts } from './texts.js'
import { getSystemPagePath } from '../pages/index.js'
import { getGlobal } from '../payload/index.js'
import { CONSENT_CATEGORIES } from './categories.js'
/** English fallback used when the global has no value for a field. */
const FALLBACK: ConsentTexts = {
buttons: {
acceptAll: 'Accept all',
back: 'Back',
reject: 'Reject',
save: 'Save preferences',
settings: 'Settings',
},
categories: {
analytics: { description: 'Help us understand usage.', title: 'Analytics' },
functional: { description: 'Remember preferences.', title: 'Functional' },
marketing: { description: 'Used to show relevant ads.', title: 'Marketing' },
necessary: {
description:
'Required for the site to work, including your language and theme preferences. Always on.',
title: 'Necessary',
},
},
message:
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.',
privacyLink: null,
settingsTitle: 'Cookie settings',
}
type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']>
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
message?: null | string
settingsTitle?: null | string
}
type GetConsentTextsArgs = {
config: I18nConfig
locale?: string
payload: BasePayload
/**
* Privacy-policy label + the system page (from SiteSettings.privacyPolicy,
* read with locale:'all') to link to. Optional — omit for no link.
*/
privacyPolicy?: {
label: string
page: { slug?: null | Record<string, unknown> } | null
}
}
/**
* Resolves consent banner texts from the CookieSettings global, falling back to
* English defaults per field. The privacy-policy link is built from the pages
* module (system page role), not stored in CookieSettings — one source of truth.
*/
export async function getConsentTexts({
config,
locale,
payload,
privacyPolicy,
}: GetConsentTextsArgs): Promise<ConsentTexts> {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
const categories = {} as ConsentTexts['categories']
for (const cat of CONSENT_CATEGORIES) {
const entry = g.categories?.find((c) => c.key === cat)
categories[cat] = {
description: entry?.description || FALLBACK.categories[cat].description,
title: entry?.title || FALLBACK.categories[cat].title,
}
}
let privacyLink: ConsentTexts['privacyLink'] = null
if (privacyPolicy?.page && locale) {
const href = getSystemPagePath({ config, locale, page: privacyPolicy.page })
if (href) {
privacyLink = { href, label: privacyPolicy.label }
}
}
return {
buttons: {
acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll,
back: g.buttons?.back || FALLBACK.buttons.back,
reject: g.buttons?.reject || FALLBACK.buttons.reject,
save: g.buttons?.save || FALLBACK.buttons.save,
settings: g.buttons?.settings || FALLBACK.buttons.settings,
},
categories,
message: g.message || FALLBACK.message,
privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
}
}
+55
View File
@@ -0,0 +1,55 @@
import type { ConsentState } from './categories.js'
type ConsentValue = 'denied' | 'granted'
type GoogleConsentSignals = Record<string, ConsentValue>
function toSignals(state: ConsentState): GoogleConsentSignals {
const g = (b: boolean): ConsentValue => (b ? 'granted' : 'denied')
return {
ad_personalization: g(state.marketing),
ad_storage: g(state.marketing),
ad_user_data: g(state.marketing),
analytics_storage: g(state.analytics),
functionality_storage: g(state.functional),
personalization_storage: g(state.functional),
security_storage: 'granted', // necessary — always on
}
}
declare global {
interface Window {
dataLayer?: unknown[]
}
}
/**
* Mirrors Google's canonical snippet: `function gtag(){dataLayer.push(arguments)}`.
*
* Pushing `arguments` rather than a plain array is not a stylistic detail.
* Google's tags recognise a consent command by the Arguments object it arrives
* in; a real array lands in the dataLayer as ordinary data and the command is
* silently ignored — the tag loads, but consent never updates and analytics
* stays denied. The rest parameter exists only to type the call sites.
*
* Exported for the analytics module (which needs `js`/`config` commands) —
* intentionally not re-exported from the package's public API.
*/
export function gtag(..._args: unknown[]) {
if (typeof window === 'undefined') {return}
window.dataLayer = window.dataLayer || []
// eslint-disable-next-line prefer-rest-params
window.dataLayer.push(arguments)
}
/** Sets the default consent state (call before Google tags load). */
export function setDefaultConsent(state: ConsentState) {
gtag('consent', 'default', {
...toSignals(state),
wait_for_update: 500, // ms to wait for an update before firing
})
}
/** Updates consent after the user decides. */
export function updateConsent(state: ConsentState) {
gtag('consent', 'update', toSignals(state))
}
+20
View File
@@ -0,0 +1,20 @@
// Server-safe exports (logic, types, helper). Client components (banner,
// provider, hook) are exported separately via ./client to keep the RSC/client
// boundary clean.
export {
ACCEPT_ALL_CONSENT,
CONSENT_CATEGORIES,
DEFAULT_CONSENT,
REJECT_ALL_CONSENT,
} from './categories.js'
export type { ConsentCategory, ConsentState } from './categories.js'
export { getConsentTexts } from './getConsentTexts.js'
export { setDefaultConsent, updateConsent } from './googleConsent.js'
export {
CONSENT_COOKIE,
CONSENT_MAX_AGE,
CONSENT_VERSION,
parseConsent,
serializeConsent,
} from './storage.js'
export type { ConsentTexts } from './texts.js'
+43
View File
@@ -0,0 +1,43 @@
import type { ConsentState } from './categories.js'
import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js'
/**
* Consent persistence in a cookie. Stored with a version so we can invalidate
* old consents when the policy changes, and a timestamp (GDPR: consent must be
* dated). Readable both client-side (banner) and server-side (script gating).
*/
export const CONSENT_COOKIE = 'cookie-consent'
export const CONSENT_VERSION = 1
export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days
type StoredConsent = {
state: ConsentState
timestamp: string
version: number
}
export function serializeConsent(state: ConsentState): string {
const payload: StoredConsent = {
state,
timestamp: new Date().toISOString(),
version: CONSENT_VERSION,
}
return encodeURIComponent(JSON.stringify(payload))
}
export function parseConsent(raw: string | undefined): ConsentState | null {
if (!raw) {return null}
try {
const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent
if (parsed.version !== CONSENT_VERSION) {return null}
const state = { ...DEFAULT_CONSENT }
for (const cat of CONSENT_CATEGORIES) {
if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]}
}
state.necessary = true
return state
} catch {
return null
}
}
+16
View File
@@ -0,0 +1,16 @@
import type { ConsentCategory } from './categories.js'
export type ConsentTexts = {
buttons: {
acceptAll: string
back: string
reject: string
save: string
settings: string
}
categories: Record<ConsentCategory, { description: string; title: string }>
message: string
/** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null
settingsTitle: string
}
+47
View File
@@ -0,0 +1,47 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import type { ConsentCategory, ConsentState } from './categories.js'
import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js'
import { updateConsent } from './googleConsent.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent, serializeConsent } from './storage.js'
export function useConsent() {
const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT)
const [decided, setDecided] = useState(false)
useEffect(() => {
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
const parsed = parseConsent(raw)
if (parsed) {
setState(parsed)
setDecided(true)
}
}, [])
const persist = useCallback((next: ConsentState) => {
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax`
setState(next)
setDecided(true)
// Tell Google right away. Tags are already on the page holding whatever
// defaults Analytics set at load; without this update they keep them for
// the rest of the session and never write their cookies — the banner would
// look like it worked while nothing changed.
updateConsent(next)
}, [])
const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist])
const rejectAll = useCallback(() => persist(REJECT_ALL_CONSENT), [persist])
const savePreferences = useCallback(
(choices: Partial<Record<ConsentCategory, boolean>>) =>
persist({ ...DEFAULT_CONSENT, ...choices, necessary: true }),
[persist],
)
const reopen = useCallback(() => setDecided(false), [])
return { acceptAll, decided, rejectAll, reopen, savePreferences, state }
}