Files
GNX-WEB/gnx-react/components/shared/layout/CookieConsentUtils.tsx
Iliyan Angelov 5ad9cbe3a6 update
2025-10-13 01:49:06 +03:00

98 lines
2.7 KiB
TypeScript

'use client';
import React, { useEffect } from 'react';
import { useCookieConsent, useCookiePermission } from './CookieConsentContext';
// Utility hook for conditional rendering based on cookie permissions
export const useConditionalFeature = (featureType: 'functional') => {
const isAllowed = useCookiePermission(featureType);
const { state } = useCookieConsent();
return {
isAllowed,
hasConsented: state.hasConsented,
canShow: isAllowed && state.hasConsented,
};
};
// Note: Analytics and marketing hooks removed as we don't collect this data
// Hook for functional features (only runs if functional cookies are allowed)
export const useFunctional = () => {
const { canShow } = useConditionalFeature('functional');
const saveUserPreference = (key: string, value: any) => {
if (canShow && typeof window !== 'undefined') {
try {
localStorage.setItem(`user-preference-${key}`, JSON.stringify(value));
} catch (error) {
}
}
};
const loadUserPreference = (key: string, defaultValue?: any) => {
if (canShow && typeof window !== 'undefined') {
try {
const saved = localStorage.getItem(`user-preference-${key}`);
return saved ? JSON.parse(saved) : defaultValue;
} catch (error) {
return defaultValue;
}
}
return defaultValue;
};
const rememberUserAction = (action: string, data?: any) => {
if (canShow) {
// Implement your user action tracking logic here
}
};
return {
saveUserPreference,
loadUserPreference,
rememberUserAction,
isEnabled: canShow,
};
};
// Component wrapper for conditional rendering
interface ConditionalFeatureProps {
feature: 'functional';
children: React.ReactNode;
fallback?: React.ReactNode;
}
export const ConditionalFeature: React.FC<ConditionalFeatureProps> = ({
feature,
children,
fallback = null,
}) => {
const { canShow } = useConditionalFeature(feature);
return canShow ? <>{children}</> : <>{fallback}</>;
};
// Example usage components (analytics and marketing removed)
export const UserPreferenceManager: React.FC<{
preferenceKey: string;
defaultValue?: any;
children: (value: any, setValue: (value: any) => void) => React.ReactNode;
}> = ({ preferenceKey, defaultValue, children }) => {
const { saveUserPreference, loadUserPreference } = useFunctional();
const [value, setValue] = React.useState(defaultValue);
useEffect(() => {
const saved = loadUserPreference(preferenceKey, defaultValue);
setValue(saved);
}, [preferenceKey, defaultValue, loadUserPreference]);
const handleSetValue = (newValue: any) => {
setValue(newValue);
saveUserPreference(preferenceKey, newValue);
};
return <>{children(value, handleSetValue)}</>;
};