File size: 1,928 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
import { useSelector } from 'calypso/state';
import isJetpackCloudEligible from 'calypso/state/selectors/is-jetpack-cloud-eligible';
import isJetpackSectionEnabledForSite from 'calypso/state/selectors/is-jetpack-section-enabled-for-site';
import { getSiteSlug } from 'calypso/state/sites/selectors';
import { getSelectedSiteId } from 'calypso/state/ui/selectors';
import type { AppState } from 'calypso/types';

/**
 * Constants
 */
const SOURCE_TO_JETPACK_PATH = {
	'calypso-scanner': '/scan/[site]',
	'calypso-backups': '/backup/[site]',
	'calypso-activity-log': '/backup/activity/[site]',
	'calypso-settings-security': '/settings/jetpack/[site]',
};

const SOURCE_TO_CALYPSO_PATH = {
	'calypso-scanner': '/activity-log/[site]',
	'calypso-backups': '/activity-log/[site]',
	'calypso-activity-log': '/activity-log/[site]',
	'calypso-settings-security': '/settings/security/[site]',
};

interface SourceToPath {
	[ key: string ]: string;
}

export function useTargetUrl( siteId: number | null ) {
	const isCloudEligible = useSelector( ( state ) =>
		isJetpackCloudEligible( state, siteId as number )
	);
	const siteSlug = useSelector( ( state ) => getSiteSlug( state, siteId as number ) );
	const shouldUseJetpackPath = useSelector( ( state: AppState ) =>
		isJetpackSectionEnabledForSite( state, siteId )
	);

	const sourceToUrl = ( source: string ): string | null => {
		if ( ! siteId ) {
			return null;
		}
		if ( isCloudEligible ) {
			return `https://jetpack.com/redirect/?source=${ source }&site=${ siteId }`;
		}

		const paths = shouldUseJetpackPath
			? ( SOURCE_TO_JETPACK_PATH as SourceToPath )
			: ( SOURCE_TO_CALYPSO_PATH as SourceToPath );

		if ( ! paths[ source ] ) {
			return source;
		}

		return paths[ source ].replace( '[site]', siteSlug ?? '' );
	};

	return sourceToUrl;
}

export function useTargetUrlForSelected() {
	const siteId = useSelector( getSelectedSiteId );
	return useTargetUrl( siteId );
}