All files / components/cookie CookieConsent.tsx

100% Statements 15/15
83.33% Branches 5/6
100% Functions 4/4
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x                           1x 6x   6x 6x 5x 5x       6x 6x 6x 1x   5x       6x         1x 1x                    
"use client";
 
import { useEffect } from "react";
import * as CookieConsent from "vanilla-cookieconsent";
import { useTheme } from "next-themes";
import pluginConfig from "./CookieConsentConfig";
 
// Extend the window object to define our custom property
declare global {
  interface Window {
    __cookieConsentInitialized?: boolean;
  }
}
 
const CookieConsentComponent = () => {
  const { theme, resolvedTheme } = useTheme();
 
  useEffect(() => {
    if (!window.__cookieConsentInitialized) {
      CookieConsent.run(pluginConfig);
      window.__cookieConsentInitialized = true; // Prevent multiple initializations
    }
  }, []);
 
  useEffect(() => {
    const currentTheme = theme || resolvedTheme;
    if (currentTheme === "dark") {
      document.documentElement.classList.add("cc--darkmode");
    } else {
      document.documentElement.classList.remove("cc--darkmode");
    }
  }, [theme, resolvedTheme]); // Sync with Next.js theme
 
  return (
    <a
      href="#"
      aria-label="Show cookie preferences"
      onClick={(e) => {
        e.preventDefault();
        CookieConsent.showPreferences();
      }}
      className="text-sm text-blue-500 underline cursor-pointer"
    >
      <span className="sr-only">Show Cookie Preferences</span>
    </a>
  );
};
 
export default CookieConsentComponent;