-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathContextualConsentsEffect.tsx
More file actions
75 lines (67 loc) · 2.04 KB
/
ContextualConsentsEffect.tsx
File metadata and controls
75 lines (67 loc) · 2.04 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {render} from 'preact';
import {ConsentsMap} from '../core/types';
import Manager from '../core/Manager';
import {Config, TitleLevel} from './types';
import Context from './components/Context';
import ContextualNoticeContainer from './components/ContextualNoticeContainer';
import ConsentsEffect from '../core/ConsentsEffect';
import {clamp} from './utils/numbers';
export default class ContextualConsentsEffect implements ConsentsEffect {
readonly #config: Config;
readonly #manager: Manager;
#containers: WeakMap<HTMLTemplateElement, HTMLDivElement>;
constructor(config: Config, manager: Manager) {
this.#config = config;
this.#manager = manager;
this.#containers = new WeakMap();
}
apply(consents: ConsentsMap) {
Object.entries(consents).forEach(([id, state]) => {
document
.querySelectorAll(`template[data-contextual][data-purpose="${id}"]`)
.forEach((template: HTMLTemplateElement) => {
this.#renderNotice(template, !state);
});
});
}
#renderNotice(template: HTMLTemplateElement, isEnabled: boolean) {
render(
<Context.Provider
value={{
config: this.#config,
manager: this.#manager
}}
>
<ContextualNoticeContainer
{...this.#parseNoticeData(template.dataset)}
isEnabled={isEnabled}
/>
</Context.Provider>,
this.#getNoticeContainer(template)
);
}
#parseNoticeData(data: DOMStringMap) {
return {
purposeId: data.purpose,
titleLevel: clamp(
parseInt(data.titleLevel, 10)
|| this.#config?.contextual?.defaultTitleLevel
|| 6,
1,
6
) as TitleLevel
};
}
#getNoticeContainer(template: HTMLTemplateElement) {
if (!this.#containers.has(template)) {
const container = document.createElement('div');
container.style.display = 'contents';
// The container is inserted before the template, so if
// the user allows cookies from inside, the revealed
// content is always after.
template.insertAdjacentElement('beforebegin', container);
this.#containers.set(template, container);
}
return this.#containers.get(template);
}
}