UNPKG

@elsikora/x-captcha-react

Version:

React components for X-Captcha service

54 lines (51 loc) 2.22 kB
import { jsx } from 'react/jsx-runtime'; import { XCaptchaApiClient } from '@elsikora/x-captcha-client'; import { createContext, useMemo, useContext } from 'react'; import { detectLanguage, createTranslator } from '../i18n/i18n.js'; import '../i18n/translations/index.js'; import styles from '../styles/captcha-widget.module.css.js'; // Create the context const CaptchaContext = createContext(null); /** * Provider component for captcha functionality * @param {ICaptchaProviderProperties} properties The properties for the provider * @returns {React.ReactElement} The provider component */ const CaptchaProvider = ({ apiUrl, children, language, publicKey }) => { // Check if publicKey is provided const isMissingPublicKey = !publicKey; // Initialize translation function const translate = useMemo(() => { const detectedLanguage = language ?? detectLanguage(); return createTranslator(detectedLanguage); }, [language]); // Create a memoized client instance to avoid unnecessary re-renders const client = useMemo(() => { if (!publicKey) { return null; } return new XCaptchaApiClient({ apiKey: publicKey, baseUrl: apiUrl, secretKey: "" }); }, [apiUrl, publicKey]); // If publicKey is missing, render an error message in captcha error style if (isMissingPublicKey) { return (jsx("div", { className: styles["x-captcha-widget"], style: { height: "74px", width: "100%" }, children: jsx("div", { className: styles["x-captcha-error"], children: jsx("div", { children: translate("missingProviderKey") }) }) })); } const value = useMemo(() => ({ // eslint-disable-next-line @elsikora/typescript/no-non-null-assertion client: client, }), [client]); return jsx(CaptchaContext, { value: value, children: children }); }; /** * Hook to use captcha functionality * @returns {ICaptchaContext} The captcha context */ const useCaptcha = () => { const context = useContext(CaptchaContext); if (!context) { throw new Error("useCaptcha must be used within a CaptchaProvider"); } return context; }; export { CaptchaProvider, useCaptcha }; //# sourceMappingURL=Captcha.context.js.map