-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathCookiePreferencesManager.tsx
120 lines (113 loc) · 3.27 KB
/
CookiePreferencesManager.tsx
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { useEffect, useMemo, useReducer } from "react"
import Cookies from "js-cookie"
import { CookiePreferences } from "../site/blocks/CookiePreferences.js"
import { CookieNotice } from "../site/CookieNotice.js"
import {
Action,
arePreferencesOutdated,
COOKIE_PREFERENCES_COOKIE_NAME,
defaultState,
getPreferenceValue,
POLICY_DATE,
PreferenceType,
serializeState,
State,
updatePreference,
} from "./cookiePreferences.js"
import { SiteAnalytics } from "./SiteAnalytics.js"
const analytics = new SiteAnalytics()
export const CookiePreferencesManager = ({
initialState,
}: {
initialState: State
}) => {
const [state, dispatch] = useReducer(reducer, initialState)
// Reset state
useEffect(() => {
if (arePreferencesOutdated(state.date, POLICY_DATE)) {
dispatch({ type: Action.Reset })
}
}, [state.date])
// Commit state
useEffect(() => {
if (state.date) {
Cookies.set(COOKIE_PREFERENCES_COOKIE_NAME, serializeState(state), {
expires: 365 * 3,
})
}
}, [state])
// Set GA consent
const analyticsConsent = useMemo(
() =>
getPreferenceValue(PreferenceType.Analytics, state.preferences)
? "granted"
: "denied",
[state.preferences]
)
useEffect(() => {
analytics.updateGAConsentSettings({
analytics_storage: analyticsConsent,
})
}, [analyticsConsent])
return (
<div data-test-policy-date={POLICY_DATE} className="cookie-manager">
<CookieNotice
accepted={!!state.date}
outdated={arePreferencesOutdated(state.date, POLICY_DATE)}
dispatch={dispatch}
/>
<CookiePreferences
preferences={state.preferences}
date={state.date?.toString()}
dispatch={dispatch}
/>
</div>
)
}
const reducer = (
state: State,
{ type: actionType, payload }: { type: Action; payload?: any }
): State => {
switch (actionType) {
case Action.Accept: {
return {
date: payload.date,
preferences: updatePreference(
PreferenceType.Analytics,
true,
state.preferences
),
}
}
case Action.TogglePreference:
return {
date: payload.date,
preferences: updatePreference(
payload.preferenceType,
!getPreferenceValue(
payload.preferenceType,
state.preferences
),
state.preferences
),
}
case Action.Reset:
return defaultState
case Action.Persist:
return {
...state,
date: payload.date,
}
case Action.Reject:
return {
date: payload.date,
preferences: updatePreference(
PreferenceType.Analytics,
false,
state.preferences
),
}
default:
return state
}
}