Skip to content

Commit

Permalink
Add Usercentrics hook + snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
apfelbox committed Apr 22, 2024
1 parent 8f1c5d3 commit fe032e5
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 1 deletion.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
2.1.2 (unreleased)
2.2.0 (unreleased)
=====

* (improvement) Add `isAbortError()`.
* (feature) Add Usercentrics hook.
* (feature) Add `<Usercentrics>` snippet component.


2.1.1
Expand Down
18 changes: 18 additions & 0 deletions src/next/components/Snippet/Usercentrics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, {ReactElement} from "react";
import Script from "next/script";

export type UsercentricsProps = Readonly<{
id: string;
}>;

export function Usercentrics (props: UsercentricsProps): ReactElement | null
{
return (
<Script
id="usercentrics-cmp"
data-settings-id={props.id}
src="https://app.usercentrics.eu/browser-ui/latest/loader.js"
async
/>
);
}
72 changes: 72 additions & 0 deletions src/react/hooks/usercentrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"use client";

import {useEffect, useState} from "react";

type WindowWithUsercentrics = Window & Readonly<{
UC_UI?: {
showFirstLayer(): void;
};
}>;

/**
* The essential key
*/
type UsercentricsConsentCategories = "essential" | "marketing" | "functional" | "statictics" | string;
type UsercentricsEvent = CustomEvent<{
ucCategory: Partial<Record<UsercentricsConsentCategories, boolean>>;
}>;



type UsercentricsSettings = Readonly<{
openConsentManager(): void;
hasAnyConsent: boolean;
/**
* Contains all categories with consent apart from the essential categories
*/
consent: Record<UsercentricsConsentCategories, boolean>;
}>;


/**
* Custom hook to integrate with user centrics
*/
export function useUsercentrics () : UsercentricsSettings
{
const [consent, setConsent] = useState<Record<UsercentricsConsentCategories, boolean>>({
marketing: false,
functional: false,
statistics: false,
});

useEffect(() =>
{
const onUsercentricsEvent = (event: UsercentricsEvent) =>
{
const newConsent: Partial<Record<UsercentricsConsentCategories, boolean>> = event.detail.ucCategory;

setConsent({
...newConsent,
marketing: newConsent.marketing ?? false,
functional: newConsent.functional ?? false,
statistics: newConsent.statistics ?? false,
});
};

window.addEventListener("ucEvent", onUsercentricsEvent as EventListener);

return () =>
{
window.removeEventListener("ucEvent", onUsercentricsEvent as EventListener);
}
}, []);

return {
consent,
hasAnyConsent: Object.keys(consent).some(category => "essential" !== category && consent[category]),
openConsentManager (): void
{
(window as WindowWithUsercentrics).UC_UI?.showFirstLayer();
},
}
}

0 comments on commit fe032e5

Please sign in to comment.