File size: 2,567 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
import { useMutation, useQueryClient, UseMutationResult } from '@tanstack/react-query';
import { useCallback } from 'react';
import wp from 'calypso/lib/wp';
import { fetchHomeLayout, getCacheKey } from './use-home-layout-query';
import { useHomeLayoutQueryParams } from './use-home-layout-query-params';

export type ReminderDuration = '1d' | '1w' | null;

interface Variables {
	reminder: ReminderDuration;
	card?: string;

	// The layout data is totally removed while the view is skipped.
	// This means the useHomeLayoutQuery will start returning `isLoading`
	resetWhileSkipping?: boolean;
}

type Result< TData, TError > = UseMutationResult< TData, TError, Variables > & {
	skipCurrentView: ( reminder: ReminderDuration ) => void;
	skipCard: ( card: string, reminder?: ReminderDuration ) => void;
};

function useSkipCurrentViewMutation< TData, TError >( siteId: number ): Result< TData, TError > {
	const queryClient = useQueryClient();
	const query = useHomeLayoutQueryParams();

	const mutation = useMutation< TData, TError, Variables >( {
		mutationFn: async ( { reminder, card, resetWhileSkipping } ) => {
			const data = await queryClient.fetchQuery( {
				queryKey: getCacheKey( siteId ),
				queryFn: () => fetchHomeLayout( siteId, query ),
				staleTime: Infinity,
			} );

			const view_name = ( data as any ).view_name;
			const multipleCardViews = [ 'VIEW_POST_LAUNCH', 'VIEW_SITE_SETUP' ];
			const isSingleCardView = multipleCardViews.indexOf( view_name ) === -1;

			if ( resetWhileSkipping ) {
				queryClient.removeQueries( { queryKey: getCacheKey( siteId ) } );
			}

			return await wp.req.post(
				{
					path: `/sites/${ siteId }/home/layout/skip`,
					apiNamespace: 'wpcom/v2',
				},
				{ query },
				{
					// Single card views are skipped by skipping the "view".
					view: isSingleCardView ? view_name : undefined,
					// Prevents single card views from returning themself after skipping
					card: isSingleCardView ? undefined : card,
					...( reminder && { reminder } ),
				}
			);
		},
		onSuccess( data ) {
			queryClient.setQueryData( getCacheKey( siteId ), data );
		},
	} );

	const { mutate } = mutation;

	const skipCurrentView = useCallback(
		( reminder: ReminderDuration, resetWhileSkipping?: boolean ) =>
			mutate( { reminder, resetWhileSkipping } ),
		[ mutate ]
	);

	const skipCard = useCallback(
		( card: string, reminder?: ReminderDuration ) => mutate( { reminder: reminder ?? null, card } ),
		[ mutate ]
	);

	return { skipCurrentView, skipCard, ...mutation };
}

export default useSkipCurrentViewMutation;