File size: 2,311 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { useState, useCallback } from 'react';
import { FixableThreat, Threat } from 'calypso/components/jetpack/threat-item/types';
import { useDispatch, useSelector } from 'calypso/state';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import {
	fixAllThreats,
	fixThreat,
	ignoreThreat,
	unignoreThreat,
} from 'calypso/state/jetpack-scan/threats/actions';
import getSiteScanUpdatingThreats from 'calypso/state/selectors/get-site-scan-updating-threats';

export const useThreats = ( siteId: number ) => {
	const [ selectedThreat, setSelectedThreat ] = useState< Threat >();
	const updatingThreats = useSelector(
		( state ) => {
			return getSiteScanUpdatingThreats( state, siteId );
		},
		( a, b ) => {
			// Compare arrays by reference first, then by contents
			if ( a === b ) {
				return true;
			}
			if ( ! a || ! b || a.length !== b.length ) {
				return false;
			}
			return a.every( ( val, idx ) => val === b[ idx ] );
		}
	);
	const dispatch = useDispatch();

	const updateThreat = useCallback(
		( action: 'fix' | 'ignore' | 'unignore' ) => {
			if ( typeof selectedThreat !== 'undefined' ) {
				let eventName;
				let actionCreator;

				switch ( action ) {
					case 'fix':
						eventName = 'calypso_jetpack_scan_threat_fix';
						actionCreator = fixThreat;
						break;
					case 'ignore':
						eventName = 'calypso_jetpack_scan_threat_ignore';
						actionCreator = ignoreThreat;
						break;
					case 'unignore':
						eventName = 'calypso_jetpack_scan_threat_unignore';
						actionCreator = unignoreThreat;
						break;
				}

				dispatch(
					recordTracksEvent( eventName, {
						site_id: siteId,
						threat_signature: selectedThreat.signature,
					} )
				);
				dispatch( actionCreator( siteId, selectedThreat.id ) );
			}
		},
		[ dispatch, selectedThreat, siteId ]
	);

	const fixThreats = useCallback(
		( fixableThreats: FixableThreat[] ) => {
			dispatch(
				recordTracksEvent( 'calypso_jetpack_scan_allthreats_fix', {
					site_id: siteId,
					threats_number: fixableThreats.length,
				} )
			);
			dispatch(
				fixAllThreats(
					siteId,
					fixableThreats.map( ( threat ) => threat.id )
				)
			);
		},
		[ dispatch, siteId ]
	);

	return {
		updatingThreats,
		selectedThreat,
		setSelectedThreat,
		fixThreats,
		updateThreat,
	};
};