All files / owid-grapher/site CookiePreferencesManager.tsx

61.41% Statements 113/184
100% Branches 26/26
66.67% Functions 6/9
61.41% Lines 113/184

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 2271x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                           1x 1x                                                                 1x 1x     1x 1x 10x 8x 8x 8x 8x 4x 4x 10x 1x 1x 1x 1x 1x 1x 1x 1x 9x 7x 7x 7x 7x 8x 8x 8x 8x 8x 8x 7x 7x 1x 1x 8x 8x 4x 8x 8x 1x 1x 14x 10x 10x 5x 5x 14x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x                                                                                      
import ReactDOM from "react-dom"
import * as React from "react"
import { useEffect, useReducer } from "react"
import * as Cookies from "js-cookie"
import { CookiePreferences } from "../site/blocks/CookiePreferences"
import { CookieNotice } from "../site/CookieNotice"
import moment from "moment"
 
export enum PreferenceType {
    Analytics = "a",
    Marketing = "m", // not used
}
 
export enum Action {
    Accept,
    TogglePreference,
    Reset,
}
 
export interface Preference {
    type: PreferenceType
    value: boolean
}
 
export const POLICY_DATE: number = 20201009
export const DATE_FORMAT = "YYYYMMDD"
const COOKIE_NAME = "cookie_preferences"
const PREFERENCES_SEPARATOR = "|"
const DATE_SEPARATOR = "-"
const PREFERENCE_KEY_VALUE_SEPARATOR = ":"
// e.g. p:1-20200910
 
interface State {
    date?: number
    preferences: Preference[]
}
 
const defaultState: State = {
    preferences: [
        {
            type: PreferenceType.Analytics,
            value: true,
        },
    ],
}
 
export const CookiePreferencesManager = ({
    initialState = defaultState,
}: {
    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_NAME, serializeState(state), {
                expires: 365 * 3,
            })
        }
    }, [state])

    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}
                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
        default:
            return state
    }
}
 
const getInitialState = (): State => {
    return parseRawCookieValue(Cookies.get(COOKIE_NAME)) ?? defaultState
}
 
export const parseRawCookieValue = (cookieValue?: string) => {
    if (!cookieValue) return
 
    const [preferencesRaw, dateRaw] = cookieValue.split(DATE_SEPARATOR)
    const date = parseDate(dateRaw)
    if (!date) return
 
    const preferences = parsePreferences(preferencesRaw)
    if (!preferences.length) return
 
    return {
        preferences,
        date,
    }
}
 
export const parsePreferences = (preferences?: string): Preference[] => {
    if (!preferences) return []
 
    return preferences
        .split(PREFERENCES_SEPARATOR)
        .map((preference) => {
            const [type, , value] = preference // only supports 1 digit values
            return {
                type: type as PreferenceType,
                value: value === "1",
            }
        })
        .filter((preference) => isValidPreference(preference))
}
 
export const isValidPreference = ({ type, value }: Preference) => {
    return (
        Object.values(PreferenceType).includes(type as PreferenceType) &&
        typeof value === "boolean"
    )
}
 
export const parseDate = (date?: string): number | undefined => {
    if (!date) return
 
    return moment(date, DATE_FORMAT, true).isValid()
        ? parseInt(date, 10)
        : undefined
}
 
export const getPreferenceValue = (
    type: PreferenceType,
    preferences: Preference[]
) => {
    return (
        preferences.find((preference) => {
            return preference.type === type
        })?.value ?? false
    )
}
 
export const updatePreference = (
    type: PreferenceType,
    value: boolean,
    preferences: Preference[]
) => {
    return preferences.map((preference) => {
        if (preference.type !== type) return preference
 
        return {
            ...preference,
            value,
        }
    })
}
 
export const arePreferencesOutdated = (
    preferencesDate: number | undefined,
    policyDate: number
) => {
    if (!preferencesDate) return false
    return preferencesDate < policyDate
}
 
export const serializeState = (state: State) => {
    const serializedPreferences = state.preferences
        .map((preference) => {
            return `${preference.type}${PREFERENCE_KEY_VALUE_SEPARATOR}${
                preference.value ? 1 : 0
            }`
        })
        .join(PREFERENCES_SEPARATOR)
 
    return `${serializedPreferences}${DATE_SEPARATOR}${state.date}`
}
 
export const getTodayDate = () => moment().format(DATE_FORMAT)
 
export const runCookiePreferencesManager = () => {
    const div = document.createElement("div")
    document.body.appendChild(div)
 
    ReactDOM.render(
        <CookiePreferencesManager initialState={getInitialState()} />,
        div
    )
}