@elsikora/x-captcha-react
Version:
React components for X-Captcha service
57 lines (53 loc) • 2.38 kB
JavaScript
;
var jsxRuntime = require('react/jsx-runtime');
var xCaptchaClient = require('@elsikora/x-captcha-client');
var react = require('react');
var i18n = require('../i18n/i18n.js');
require('../i18n/translations/index.js');
var captchaWidget_module = require('../styles/captcha-widget.module.css.js');
// Create the context
const CaptchaContext = react.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 = react.useMemo(() => {
const detectedLanguage = language ?? i18n.detectLanguage();
return i18n.createTranslator(detectedLanguage);
}, [language]);
// Create a memoized client instance to avoid unnecessary re-renders
const client = react.useMemo(() => {
if (!publicKey) {
return null;
}
return new xCaptchaClient.XCaptchaApiClient({ apiKey: publicKey, baseUrl: apiUrl, secretKey: "" });
}, [apiUrl, publicKey]);
// If publicKey is missing, render an error message in captcha error style
if (isMissingPublicKey) {
return (jsxRuntime.jsx("div", { className: captchaWidget_module.default["x-captcha-widget"], style: { height: "74px", width: "100%" }, children: jsxRuntime.jsx("div", { className: captchaWidget_module.default["x-captcha-error"], children: jsxRuntime.jsx("div", { children: translate("missingProviderKey") }) }) }));
}
const value = react.useMemo(() => ({
// eslint-disable-next-line @elsikora/typescript/no-non-null-assertion
client: client,
}), [client]);
return jsxRuntime.jsx(CaptchaContext, { value: value, children: children });
};
/**
* Hook to use captcha functionality
* @returns {ICaptchaContext} The captcha context
*/
const useCaptcha = () => {
const context = react.useContext(CaptchaContext);
if (!context) {
throw new Error("useCaptcha must be used within a CaptchaProvider");
}
return context;
};
exports.CaptchaProvider = CaptchaProvider;
exports.useCaptcha = useCaptcha;
//# sourceMappingURL=Captcha.context.js.map