Files
ipal-kit/src/modules/turnstile/TurnstileProvider.tsx
T

112 lines
4.0 KiB
TypeScript

'use client'
import { createContext, use, useCallback, useState } from 'react'
import type { TurnstileTheme } from './Turnstile.js'
import { Turnstile } from './Turnstile.js'
type TurnstileContextValue = {
/** Clears the token and makes the widget issue a new one. */
reset: () => void
/** Bumped by `reset` — the widget re-runs its challenge when it changes. */
resetSignal: number
setToken: (t: null | string) => void
/** Public site key from the provider (read server-side, passed once). */
siteKey: null | string
/** Current token (null until solved / after expiry). */
token: null | string
}
const TurnstileContext = createContext<null | TurnstileContextValue>(null)
/**
* Provides the Turnstile site key once for the whole app, like ConsentProvider
* for cookies. The project reads the key server-side and passes it here in the
* layout; forms then use <TurnstileWidget /> + useTurnstile() with NO per-form
* key wiring.
*
* // layout.tsx (server) → read key, pass to provider
* import { TurnstileProvider } from '@intecion/ipal-kit/client'
* import { getTurnstileConfig } from '@intecion/ipal-kit'
* const { siteKey } = await getTurnstileConfig(payload) // null unless both keys are set
* <TurnstileProvider siteKey={siteKey}>{children}</TurnstileProvider>
*
* When siteKey is null (Turnstile not configured), widgets render nothing and
* token stays null — submitForm skips the check too, so the form just works.
*/
export function TurnstileProvider({
children,
siteKey,
}: {
children: React.ReactNode
siteKey: null | string
}) {
const [token, setToken] = useState<null | string>(null)
const [resetSignal, setResetSignal] = useState(0)
const reset = useCallback(() => {
setToken(null)
setResetSignal((n) => n + 1)
}, [])
return (
<TurnstileContext value={{ reset, resetSignal, setToken, siteKey, token }}>
{children}
</TurnstileContext>
)
}
/**
* Hook giving a form the Turnstile token + a widget bound to the provider's key.
* No per-form siteKey plumbing — the provider supplies it.
*
* const { token, TurnstileWidget, reset } = useTurnstile()
* // in JSX: <TurnstileWidget />
* // at submit: submitForm({ ..., turnstileToken: token })
* // after a refused submit: reset() // the token is spent — the widget issues a new one
*/
export function useTurnstile(): {
/** True when Turnstile is configured (site key present). */
enabled: boolean
reset: () => void
token: null | string
TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
} {
const ctx = use(TurnstileContext)
if (!ctx) {
throw new Error('useTurnstile must be used within <TurnstileProvider>')
}
return useTurnstileFrom(ctx)
}
const NO_PROVIDER: TurnstileContextValue = { reset: () => {}, resetSignal: 0, setToken: () => {}, siteKey: null, token: null }
/**
* useTurnstile without the provider requirement: outside <TurnstileProvider>
* it reports `enabled: false` (no widget, no token) instead of throwing. For
* shared components (BuilderForm) that must not crash a page missing the provider.
*/
export function useOptionalTurnstile(): ReturnType<typeof useTurnstile> {
return useTurnstileFrom(use(TurnstileContext) ?? NO_PROVIDER)
}
function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurnstile> {
const { reset, siteKey, token } = ctx
const TurnstileWidget = useCallback(
(props?: { theme?: TurnstileTheme }) => {
if (!siteKey) {return null}
return <ProvidedTurnstile theme={props?.theme} />
},
[siteKey],
)
return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
}
/** The provider's widget: reads the key and the reset signal from the context, so `reset()` reaches it without a remount. */
function ProvidedTurnstile({ theme }: { theme?: TurnstileTheme }) {
const ctx = use(TurnstileContext)
if (!ctx?.siteKey) {return null}
return <Turnstile onToken={ctx.setToken} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
}