nextjs-cookie-consent 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"CookieBanner.d.ts","sourceRoot":"","sources":["../../src/CookieBanner.tsx"],"names":[],"mappings":"AAEA,OAAO,KAA8B,MAAM,OAAO,CAAC;AACnD,OAAO,EAAgC,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAwD1E,QAAA,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAkJ7C,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"CookieBanner.d.ts","sourceRoot":"","sources":["../../src/CookieBanner.tsx"],"names":[],"mappings":"AAEA,OAAO,KAA8B,MAAM,OAAO,CAAC;AACnD,OAAO,EAAgB,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAkE1D,QAAA,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAwI7C,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -54,29 +54,35 @@ const styles = {
54
54
  textDecoration: 'underline'
55
55
  }
56
56
  };
57
+ const objectsEqual = (a, b) => {
58
+ const aKeys = Object.keys(a);
59
+ const bKeys = Object.keys(b);
60
+ if (aKeys.length !== bKeys.length)
61
+ return false;
62
+ for (const key of aKeys) {
63
+ if (a[key] !== b[key])
64
+ return false;
65
+ }
66
+ return true;
67
+ };
57
68
  const CookieBanner = ({ categories, content, storageStrategy = 'localStorage' }) => {
58
- const categoryKeys = categories.map((c) => c.key);
69
+ const categoryKeys = categories.map(c => c.key);
59
70
  const { consent, isSet, saveConsent, isInitialized } = useConsent(categoryKeys, storageStrategy);
60
71
  const [showSettings, setShowSettings] = useState(false);
61
72
  const [tempConsent, setTempConsent] = useState({});
62
- // Update tempConsent whenever consent changes
63
73
  useEffect(() => {
64
- if (isInitialized) {
74
+ if (isInitialized && !objectsEqual(tempConsent, consent)) {
65
75
  setTempConsent(consent);
66
76
  }
67
77
  }, [consent, isInitialized]);
68
- // Don't render anything until initialized to prevent hydration mismatches
69
- if (!isInitialized)
70
- return null;
71
- // Don't show banner if consent is already set
72
- if (isSet)
78
+ if (!isInitialized || isSet)
73
79
  return null;
74
80
  const updateTemp = (key, value) => {
75
- setTempConsent((prev) => (Object.assign(Object.assign({}, prev), { [key]: value })));
81
+ setTempConsent(prev => (Object.assign(Object.assign({}, prev), { [key]: value })));
76
82
  };
77
83
  const acceptAll = () => {
78
84
  const allTrue = { necessary: true };
79
- categoryKeys.forEach((key) => {
85
+ categoryKeys.forEach(key => {
80
86
  allTrue[key] = true;
81
87
  });
82
88
  saveConsent(allTrue);
@@ -86,7 +92,7 @@ const CookieBanner = ({ categories, content, storageStrategy = 'localStorage' })
86
92
  };
87
93
  const acceptNecessaryOnly = () => {
88
94
  const necessaryOnly = { necessary: true };
89
- categoryKeys.forEach((key) => {
95
+ categoryKeys.forEach(key => {
90
96
  necessaryOnly[key] = false;
91
97
  });
92
98
  saveConsent(necessaryOnly);
@@ -97,6 +103,6 @@ const CookieBanner = ({ categories, content, storageStrategy = 'localStorage' })
97
103
  const handleButtonLeave = (e) => {
98
104
  e.currentTarget.style.backgroundColor = '#111';
99
105
  };
100
- return (_jsx("div", { style: styles.cookieBanner, className: "njs-cookie-banner-container", children: !showSettings ? (_jsxs("div", { style: styles.cookieBannerBasic, className: "njs-cookie-banner-default", children: [_jsx("div", { style: styles.cookieBannerText, children: content || (_jsxs("p", { children: ["We use cookies to improve your experience.", ' ', _jsx("a", { href: "/privacy-policy", target: "_blank", rel: "noopener noreferrer", style: styles.cookieBannerTextLink, children: "Learn more" }), "."] })) }), _jsxs("div", { style: styles.cookieBannerButtons, className: "njs-cookie-banner-buttons", children: [_jsx("button", { className: "njs-cookie-banner-button-necessary", style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: acceptNecessaryOnly, children: "Only necessary" }), _jsx("button", { className: "njs-cookie-banner-button-settings", style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: () => setShowSettings(true), children: "Settings" }), _jsx("button", { className: "njs-cookie-banner-button-all", style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: acceptAll, children: "Accept all" })] })] })) : (_jsxs("div", { style: styles.cookieBannerSettings, className: "njs-cookie-banner-settings", children: [_jsx("h4", { className: "njs-cookie-banner-settings-heading", children: "Cookie Settings" }), _jsxs("label", { style: styles.cookieBannerSettingsLabel, className: "njs-cookie-banner-category", children: [_jsx("input", { type: "checkbox", checked: true, disabled: true }), "Necessary (always active)"] }), categories.map((cat) => (_jsxs("label", { style: styles.cookieBannerSettingsLabel, className: "njs-cookie-banner-category", children: [_jsx("input", { type: "checkbox", checked: tempConsent[cat.key] || false, onChange: (e) => updateTemp(cat.key, e.target.checked) }), cat.label] }, cat.key))), _jsxs("div", { style: styles.cookieBannerButtons, className: "njs-cookie-banner-buttons", children: [_jsx("button", { className: "njs-cookie-banner-button-save", style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: saveSelected, children: "Save" }), _jsx("button", { className: "njs-cookie-banner-button-back", style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: () => setShowSettings(false), children: "Back" })] })] })) }));
106
+ return (_jsx("div", { style: styles.cookieBanner, className: "njs-cookie-banner-container", children: !showSettings ? (_jsxs("div", { style: styles.cookieBannerBasic, children: [_jsx("div", { style: styles.cookieBannerText, children: content || (_jsxs("p", { children: ["We use cookies to improve your experience.", ' ', _jsx("a", { href: "/privacy-policy", target: "_blank", rel: "noopener noreferrer", style: styles.cookieBannerTextLink, children: "Learn more" }), "."] })) }), _jsxs("div", { style: styles.cookieBannerButtons, children: [_jsx("button", { style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: acceptNecessaryOnly, children: "Only necessary" }), _jsx("button", { style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: () => setShowSettings(true), children: "Settings" }), _jsx("button", { style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: acceptAll, children: "Accept all" })] })] })) : (_jsxs("div", { style: styles.cookieBannerSettings, children: [_jsx("h4", { children: "Cookie Settings" }), _jsxs("label", { style: styles.cookieBannerSettingsLabel, children: [_jsx("input", { type: "checkbox", checked: true, disabled: true }), "Necessary (always active)"] }), categories.map(cat => (_jsxs("label", { style: styles.cookieBannerSettingsLabel, children: [_jsx("input", { type: "checkbox", checked: tempConsent[cat.key] || false, onChange: e => updateTemp(cat.key, e.target.checked) }), cat.label] }, cat.key))), _jsxs("div", { style: styles.cookieBannerButtons, children: [_jsx("button", { style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: saveSelected, children: "Save" }), _jsx("button", { style: styles.cookieBannerButton, onMouseEnter: handleButtonHover, onMouseLeave: handleButtonLeave, onClick: () => setShowSettings(false), children: "Back" })] })] })) }));
101
107
  };
102
108
  export default CookieBanner;
@@ -1,5 +1,5 @@
1
- import { ConsentState, StorageStrategy } from './types';
2
- export declare function useConsent(categoryKeys: string[], storageStrategy?: StorageStrategy): {
1
+ import { ConsentState } from './types';
2
+ export declare const useConsent: (categoryKeys: string[], storageStrategy?: "localStorage" | "cookie") => {
3
3
  consent: ConsentState;
4
4
  isSet: boolean;
5
5
  saveConsent: (newConsent: ConsentState) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"useConsent.d.ts","sourceRoot":"","sources":["../../src/useConsent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAExD,wBAAgB,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,EAAE,eAAe,GAAE,eAAgC;;;8BAsEnD,YAAY;;EAc5D"}
1
+ {"version":3,"file":"useConsent.d.ts","sourceRoot":"","sources":["../../src/useConsent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AA0BvC,eAAO,MAAM,UAAU,GACnB,cAAc,MAAM,EAAE,EACtB,kBAAiB,cAAc,GAAG,QAAyB;;;8BAe1B,YAAY,KAAG,IAAI;;CAYvD,CAAC"}
@@ -1,80 +1,48 @@
1
- import { useState, useEffect, useCallback, useMemo } from 'react';
2
- export function useConsent(categoryKeys, storageStrategy = 'localStorage') {
3
- const storageKey = 'cookie-consent';
4
- // Memoize defaultConsent to prevent unnecessary re-renders
5
- const defaultConsent = useMemo(() => (Object.assign({ necessary: true }, categoryKeys.reduce((acc, key) => {
6
- acc[key] = false;
7
- return acc;
8
- }, {}))), [categoryKeys]);
9
- const getStoredConsent = useCallback(() => {
10
- try {
11
- if (typeof window === 'undefined')
12
- return null; // SSR check
13
- if (storageStrategy === 'localStorage') {
14
- const stored = localStorage.getItem(storageKey);
15
- return stored ? JSON.parse(stored) : null;
16
- }
17
- else {
18
- const match = document.cookie.match(new RegExp('(^| )' + storageKey + '=([^;]+)'));
19
- return match ? JSON.parse(decodeURIComponent(match[2])) : null;
20
- }
21
- }
22
- catch (error) {
23
- console.warn('Error reading consent from storage:', error);
24
- return null;
25
- }
26
- }, [storageStrategy]);
27
- const storeConsent = useCallback((consent) => {
28
- try {
29
- if (typeof window === 'undefined')
30
- return; // SSR check
31
- const encoded = JSON.stringify(consent);
32
- if (storageStrategy === 'localStorage') {
33
- localStorage.setItem(storageKey, encoded);
34
- }
35
- else {
36
- const expires = new Date();
37
- expires.setFullYear(expires.getFullYear() + 1);
38
- document.cookie = `${storageKey}=${encodeURIComponent(encoded)}; path=/; SameSite=Lax; expires=${expires.toUTCString()}`;
39
- }
40
- }
41
- catch (error) {
42
- console.error('Error storing consent:', error);
43
- }
44
- }, [storageStrategy]);
45
- const [consent, setConsent] = useState(defaultConsent);
1
+ import { useState, useEffect } from 'react';
2
+ const CONSENT_KEY = 'user_consent';
3
+ function getStoredConsent(strategy) {
4
+ var _a;
5
+ try {
6
+ const data = strategy === 'localStorage'
7
+ ? localStorage.getItem(CONSENT_KEY)
8
+ : decodeURIComponent(((_a = document.cookie.split('; ')
9
+ .find(row => row.startsWith(CONSENT_KEY + '='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || '');
10
+ return data ? JSON.parse(data) : null;
11
+ }
12
+ catch (_b) {
13
+ return null;
14
+ }
15
+ }
16
+ function storeConsent(consent, strategy) {
17
+ const value = JSON.stringify(consent);
18
+ if (strategy === 'localStorage') {
19
+ localStorage.setItem(CONSENT_KEY, value);
20
+ }
21
+ else {
22
+ document.cookie = `${CONSENT_KEY}=${encodeURIComponent(value)}; path=/; max-age=31536000`;
23
+ }
24
+ }
25
+ export const useConsent = (categoryKeys, storageStrategy = 'localStorage') => {
26
+ const [consent, setConsent] = useState({});
46
27
  const [isSet, setIsSet] = useState(false);
47
- const [isInitialized, setIsInitialized] = useState(false);
48
- // Initialize consent from storage
28
+ const [isInitialized, setInitialized] = useState(false);
49
29
  useEffect(() => {
50
- if (typeof window === 'undefined')
51
- return;
52
- const stored = getStoredConsent();
30
+ const stored = getStoredConsent(storageStrategy);
53
31
  if (stored) {
54
- // Merge stored consent with default consent to ensure all categories are present
55
- // This handles cases where new categories were added after the user already gave consent
56
- const mergedConsent = Object.assign(Object.assign({}, defaultConsent), stored);
57
- setConsent(mergedConsent);
32
+ setConsent(stored);
58
33
  setIsSet(true);
59
34
  }
60
- else {
61
- // No stored consent found, use default
62
- setConsent(defaultConsent);
63
- setIsSet(false);
64
- }
65
- setIsInitialized(true);
66
- }, [defaultConsent, getStoredConsent]);
67
- const saveConsent = useCallback((newConsent) => {
68
- const finalConsent = Object.assign({ necessary: true }, newConsent); // Ensure necessary is always true
69
- storeConsent(finalConsent);
70
- setConsent(finalConsent);
35
+ setInitialized(true);
36
+ }, []);
37
+ const saveConsent = (newConsent) => {
38
+ setConsent(newConsent);
71
39
  setIsSet(true);
72
- }, [storeConsent]);
73
- // Return isInitialized to prevent rendering issues during SSR/hydration
40
+ storeConsent(newConsent, storageStrategy);
41
+ };
74
42
  return {
75
43
  consent,
76
- isSet: isSet && isInitialized,
44
+ isSet,
77
45
  saveConsent,
78
46
  isInitialized
79
47
  };
80
- }
48
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nextjs-cookie-consent",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "GDPR-compliant cookie consent banner with fully customizable categories for Next.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",