File size: 2,103 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
	recordTracksEvent,
	getTrackingPrefs,
	setTrackingPrefs,
	isRegionInCcpaZone,
} from '@automattic/calypso-analytics';
import cookie from 'cookie';
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { saveUserSettings } from 'calypso/state/user-settings/actions';
import { refreshCountryCodeCookieGdpr } from '.';

export default () => {
	const [ shouldSeeDoNotSell, setShouldSeeDoNotSell ] = useState( false );
	const [ isDoNotSell, setIsDoNotSell ] = useState( false );
	const dispatch = useDispatch();

	useEffect( () => {
		const controller = new AbortController();

		refreshCountryCodeCookieGdpr( controller.signal )
			.then( () => {
				const cookies = cookie.parse( document.cookie );

				setShouldSeeDoNotSell( isRegionInCcpaZone( cookies.country_code, cookies.region ) );
			} )
			.catch( () => {
				// Fail safe: in case of error, we offer Do Not Sell anyway
				setShouldSeeDoNotSell( true );
			} );

		return () => controller.abort();
	}, [ setShouldSeeDoNotSell ] );

	useEffect( () => {
		// We set initial `isDoNotSell` via hook to make sure it run only on client side (when SSR)
		setIsDoNotSell( ! getTrackingPrefs().buckets.advertising );
	}, [] );

	const setUserAdvertisingOptOut = useCallback(
		( isOptedOut: boolean ) => {
			dispatch( saveUserSettings( { advertising_targeting_opt_out: isOptedOut } ) );
		},
		[ saveUserSettings ]
	);

	const onSetDoNotSell = useCallback(
		( isActive: boolean ) => {
			// Update the preferences in the cookie
			// isActive = true means user has opted out of "advertising" tracking
			const prefs = setTrackingPrefs( { ok: true, buckets: { advertising: ! isActive } } );

			if ( isActive ) {
				recordTracksEvent( 'a8c_ccpa_optout', {
					source: 'calypso',
					hostname: window.location.hostname,
					pathname: window.location.pathname,
				} );
			}

			setUserAdvertisingOptOut( isActive );
			setIsDoNotSell( ! prefs.buckets.advertising );
		},
		[ setIsDoNotSell ]
	);

	return { shouldSeeDoNotSell, onSetDoNotSell, setUserAdvertisingOptOut, isDoNotSell };
};