Back

94.73% Statements 18/19
95.45% Branches 21/22
100% Functions 3/3
94.73% Lines 18/19

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              5x                         8x 8x   8x 8x 4x   4x 4x 4x 3x                       4x 1x   4x     4x 1x   4x 1x   4x    
import { getThreatType, type Threat } from '@automattic/jetpack-scan';
import { useEffect, useRef } from '@wordpress/element';
import { recordEvent } from './analytics';
import type { ScanThreat } from '../sections/scan/types';
import type { View } from '@wordpress/dataviews';
 
// The Protect plugin's singular names for each kind of threat.
const OPEN_KINDS: Record< string, string > = {
	core: 'core',
	plugins: 'plugin',
	themes: 'theme',
	file: 'file',
};
 
/**
 * Record a threat's details opening, once per threat while the inspector stays open.
 *
 * @param threat - The threat shown, or undefined while there is none.
 */
export function useRecordThreatOpen( threat?: ScanThreat ): void {
	const id = threat && String( threat.id );
	const recorded = useRef< string >();
 
	useEffect( () => {
		if ( ! threat || recorded.current === id ) {
			return;
		}
		recorded.current = id;
		const kind = OPEN_KINDS[ getThreatType( threat as Threat ) ?? '' ];
		if ( kind ) {
			recordEvent( `jetpack_protect_${ kind }_threat_open` );
		}
	}, [ threat, id ] );
}
 
/**
 * Record what changed in a threats table's view, named like the Scan page's threats table.
 *
 * @param previous - The view before the change.
 * @param next     - The view after it.
 */
export function recordViewChange( previous: View, next: View ): void {
	if ( previous.search !== next.search ) {
		recordEvent( 'jetpack_scan_search', { has_query: !! next.search } );
	}
	Iif ( previous.type !== next.type ) {
		recordEvent( 'jetpack_scan_layout_changed', { layout: next.type } );
	}
	if ( previous.page !== next.page ) {
		recordEvent( 'jetpack_scan_page_change', { page: next.page } );
	}
	if ( JSON.stringify( previous.filters ?? [] ) !== JSON.stringify( next.filters ?? [] ) ) {
		recordEvent( 'jetpack_scan_filter_change' );
	}
	recordEvent( 'jetpack_scan_view_change' );
}