File size: 1,731 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
import { addQueryArgs } from '@wordpress/url';
import { useHref, useLocation } from 'react-router';
import { getLoginUrl } from '../utils/path';
import { useFlowLocale } from './use-flow-locale';
import { useSiteData } from './use-site-data';
import type { Flow, FlowV2 } from 'calypso/landing/stepper/declarative-flow/internals/types';

type UseLoginUrlForFlowProps = {
	flow: Flow | FlowV2< any >;
};

export function useLoginUrlForFlow( { flow }: UseLoginUrlForFlowProps ): string {
	const locale = useFlowLocale();
	const location = useLocation();
	const { siteId, siteSlug } = useSiteData();
	const path = useHref( location.pathname );
	const { extraQueryParams, customLoginPath } = flow.useLoginParams?.() ?? {};

	return getLoginUrlForFlow( {
		flow,
		path,
		locale,
		siteId,
		siteSlug,
		search: location.search,
		extraQueryParams,
		customLoginPath,
	} );
}

type GetLoginUrlForFlowProps = {
	flow: Flow | FlowV2< any >;
	path: string;
	locale: string;
	siteId: string | number;
	siteSlug: string;
	search?: string;
	extraQueryParams?: Record< string, string | number >;
	customLoginPath?: string;
};

export function getLoginUrlForFlow( {
	flow,
	path,
	locale,
	siteId,
	siteSlug,
	search = window.location.search,
	extraQueryParams = {},
	customLoginPath,
}: GetLoginUrlForFlowProps ): string {
	const redirectTo = addQueryArgs( path, {
		...( locale && locale !== 'en' ? { locale } : {} ),
		...( siteId ? { siteId } : {} ),
		...( siteSlug ? { siteSlug } : {} ),
		...Object.fromEntries( new URLSearchParams( search ).entries() ),
	} );

	return getLoginUrl( {
		variationName: flow.variantSlug ?? flow.name,
		pageTitle: flow.title,
		locale,
		redirectTo,
		extra: extraQueryParams,
		customLoginPath,
	} );
}