60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
import { useCallback } from "react";
|
|
|
|
import { KETCH_RETRY_CONFIG } from "~/constants";
|
|
import { KetchConsentResponse } from "~/types";
|
|
|
|
export const useConsent = () => {
|
|
const setupAnalyticsConsentListener = useCallback(
|
|
(onConsentChange: (hasConsent: boolean) => void) => {
|
|
let retries = 0;
|
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
if (process.env.NODE_ENV === "development") {
|
|
onConsentChange(true);
|
|
return () => {
|
|
// noop cleanup for dev
|
|
};
|
|
}
|
|
|
|
const trySetup = () => {
|
|
if ("window" in globalThis && window.ketch) {
|
|
try {
|
|
window.ketch(
|
|
"on",
|
|
"consent",
|
|
(consentData: KetchConsentResponse) => {
|
|
onConsentChange(Boolean(consentData.purposes?.analytics));
|
|
}
|
|
);
|
|
} catch (error) {
|
|
console.error("Failed to setup Ketch consent listener:", error);
|
|
onConsentChange(false);
|
|
}
|
|
} else if (retries < KETCH_RETRY_CONFIG.maxRetries) {
|
|
retries++;
|
|
timeoutId = setTimeout(trySetup, KETCH_RETRY_CONFIG.retryInterval);
|
|
} else {
|
|
console.warn(
|
|
`Failed to initialize consent management after ${KETCH_RETRY_CONFIG.maxRetries} retries`
|
|
);
|
|
onConsentChange(false);
|
|
}
|
|
};
|
|
|
|
trySetup();
|
|
|
|
// Return cleanup function to cancel pending retries
|
|
return () => {
|
|
if (timeoutId !== null) {
|
|
clearTimeout(timeoutId);
|
|
}
|
|
};
|
|
},
|
|
[]
|
|
);
|
|
|
|
return {
|
|
setupAnalyticsConsentListener,
|
|
};
|
|
};
|