'use client'; import { FC, useCallback, useEffect, useState } from 'react'; import Cookies from 'js-cookie'; import { ComponentParameter, UniformSlot, UniformText } from '@uniformdev/next-app-router/component'; import BaseBanner, { BannerVariants } from '@/components/ui/Banner'; import BaseButton from '@/components/ui/Button'; import useCookiesConsent from '@/utils/useCookiesConsent'; import { withFlattenParameters } from '@/utils/withFlattenParameters'; import { CookieConsentProps, CookieConsentParameters } from '.'; const CLIENT_COOKIE_NAME = 'hasAcceptedCookies'; const CookieConsent: FC = ({ backgroundColor, spacing, border, fluidContent, allowTextColor, allowButtonColor, allowButtonHoverColor, declineTextColor, declineButtonColor, declineButtonHoverColor, slots, variant, parameters, component, context, }) => { const [showCookieConsent, setShowCookieConsent] = useState(false); const { consent, updateConsent } = useCookiesConsent(); const { defaultConsent } = context?.pageState || {}; useEffect(() => { // get user has accepted cookies from cookie const cookieValue = Cookies.get(CLIENT_COOKIE_NAME); const userHasAcceptedCookies = cookieValue === undefined ? undefined : cookieValue === 'true'; if (userHasAcceptedCookies === undefined) { // if user has not accepted cookies and default consent is false, show cookie consent if (!defaultConsent) { // eslint-disable-next-line react-hooks/set-state-in-effect setShowCookieConsent(true); // if consent is true, but user has not accepted cookies, update consent to false if (consent) { updateConsent(false); } } return; } // if user has accepted cookies and consent is not the same, update consent if (consent !== userHasAcceptedCookies) { updateConsent(userHasAcceptedCookies); } }, [defaultConsent, consent, updateConsent, setShowCookieConsent]); const handleAllowCookiesButtonClick = useCallback(() => { updateConsent(true); Cookies.set(CLIENT_COOKIE_NAME, 'true'); setShowCookieConsent(false); }, [updateConsent]); const handleDeclineCookiesButtonClick = useCallback(() => { updateConsent(false); Cookies.set(CLIENT_COOKIE_NAME, 'false'); setShowCookieConsent(false); }, [updateConsent]); if (!showCookieConsent) return null; return (
} component={component} /> } component={component} />
); }; export default withFlattenParameters(CookieConsent);