Files
ipal-kit/src/modules/consent/ConsentScript.tsx
T
radoslaw.smolinskiandClaude Opus 5.5 ab854ef37a MCP site tools, Turnstile key alert, required 2FA injection, a11y, more tests
- MCP: new get_site_info and list_pages tools (public by design, published
  and indexable content only); search results collapse the homepage to root.
  New listContent() helper shared with searchContent.
- Dashboard alert when Turnstile is half-configured (it is silently off then).
- twoFactor.plugin is now required; the dynamic-import fallback (which never
  worked under Next and caused a Turbopack warning) is gone.
- a11y: cookie category checkboxes are labelled, buttons have type, test-email
  input is labelled; tab labels keep localized collection labels.
- IPAL_IP_HEADER: one-time production warning when unset, opt-in
  ipalEnvRules({ ipHeader: true }).
- Tests: SEO/robots/sitemap/hreflang, CSP, Markdown, consent, MCP, and a real
  Payload + SQLite integration test for forms and the roles guard (74 total).
- Drop unused mongodb-memory-server; dev .env.example for SQLite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 01:15:19 +02:00

111 lines
4.0 KiB
TypeScript

'use client'
import { useEffect, useRef } from 'react'
import type { ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
type ConsentScriptProps = {
/** Default true. */
async?: boolean
/** Extra attributes on the <script> (e.g. { 'data-domain': 'x.com' }). */
attributes?: Record<string, string>
/**
* Consent category that must be granted before the script loads. Typically
* 'analytics' (GA, Plausible) or 'marketing' (Meta Pixel, ads, chat widgets).
*/
category: ConsentCategory
/**
* Inline JS to run once granted. If `src` is also set, it runs after the
* external script loads (so init code can rely on the library). A plain
* string of code — NOT user input (you control it), it goes into a <script>.
*/
code?: string
defer?: boolean
/** Stable id used to dedupe — the script is injected at most once. */
id?: string
/** External script URL. Injected only once the category is granted. */
src?: string
}
/**
* Loads a third-party script ONLY after the visitor has granted consent for its
* category — the GDPR-correct default for anything that isn't strictly
* necessary. Renders nothing until then. Reacts live to the consent context, so
* a script appears the moment the visitor accepts in the banner, with no reload.
*
* Use this for third parties that have NO Google Consent Mode of their own (Meta
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
* handled by Consent Mode (the module's updateConsent already does that) — reach
* for ConsentScript when a vendor can't be gated that way.
*
* Must be rendered inside <ConsentProvider>.
*
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
* <ConsentScript category="analytics"
* src="https://plausible.io/js/script.js"
* attributes={{ 'data-domain': 'example.com' }} />
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
*
* Note on withdrawal: once a script has loaded it keeps running for that page
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
* load. For vendors that support it, prefer Consent Mode so running tags honor
* the change immediately; ConsentScript gates the initial load.
*/
export function ConsentScript({
id,
async: asyncAttr = true,
attributes,
category,
code,
defer,
src,
}: ConsentScriptProps) {
const { state } = useConsentContext()
const granted = state[category] === true
const injectedRef = useRef(false)
useEffect(() => {
if (!granted || injectedRef.current) {return}
if (!src && !code) {return}
const dedupeId = id ?? (src ? `ipal-cs-${src}` : undefined)
if (dedupeId && document.getElementById(dedupeId)) {
injectedRef.current = true
return
}
injectedRef.current = true
const runInline = () => {
if (!code) {return}
const inline = document.createElement('script')
if (dedupeId) {inline.id = `${dedupeId}-inline`}
inline.textContent = code
document.head.appendChild(inline)
}
if (src) {
const el = document.createElement('script')
el.src = src
if (dedupeId) {el.id = dedupeId}
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
// eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- one-shot, and the script is never unloaded (see below)
el.addEventListener('load', runInline, { once: true })
document.head.appendChild(el)
} else {
runInline()
}
// Deliberately no removal on cleanup: a loaded third-party script can't be
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
// vendors that support it, Consent Mode). See the component doc.
}, [granted, src, code, id, attributes, asyncAttr, defer])
return null
}
export default ConsentScript