File size: 3,656 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { useState, useCallback, useEffect } from 'react';
import { useUrlBasicMetricsQuery } from 'calypso/data/site-profiler/use-url-basic-metrics-query';
import { useUrlPerformanceInsightsQuery } from 'calypso/data/site-profiler/use-url-performance-insights';
import { TabType } from 'calypso/performance-profiler/components/header';
import { isValidURL } from '../utils';

export const usePerformanceReport = (
	setIsSavingPerformanceReportUrl: ( isSaving: boolean ) => void,
	refetchPages: () => void,
	savePerformanceReportUrl: (
		pageId: string,
		wpcom_performance_report_url: { url: string; hash: string }
	) => Promise< void >,
	currentPageId: string,
	wpcom_performance_report_url: { url: string; hash: string } | undefined,
	activeTab: TabType
) => {
	const { url = '', hash = '' } = wpcom_performance_report_url || {};

	const [ retestState, setRetestState ] = useState( 'idle' );

	const {
		data: basicMetrics,
		isError: isBasicMetricsError,
		isFetched: isBasicMetricsFetched,
		isLoading: isLoadingBasicMetrics,
		refetch: requeueAdvancedMetrics,
	} = useUrlBasicMetricsQuery( url, hash, true );

	const { final_url: finalUrl, token } = basicMetrics || {};

	useEffect( () => {
		if ( token && finalUrl && isValidURL( finalUrl ) ) {
			setIsSavingPerformanceReportUrl( true );
			savePerformanceReportUrl( currentPageId, { url: finalUrl, hash: token } )
				.then( () => {
					refetchPages();
				} )
				.finally( () => {
					setIsSavingPerformanceReportUrl( false );
				} );
		}
		// We only want to run this effect when the token changes.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ token ] );

	const {
		data,
		status: insightsStatus,
		isError: isInsightsError,
		isLoading: isLoadingInsights,
	} = useUrlPerformanceInsightsQuery( url, token ?? hash );

	const performanceInsights = data?.pagespeed;

	const isReportFailed = ( report: unknown ) => report === 'failed';

	const mobileReport =
		typeof performanceInsights?.mobile === 'string' ? undefined : performanceInsights?.mobile;
	const desktopReport =
		typeof performanceInsights?.desktop === 'string' ? undefined : performanceInsights?.desktop;

	const performanceReport = activeTab === 'mobile' ? mobileReport : desktopReport;

	const desktopLoaded =
		typeof performanceInsights?.desktop === 'object' || performanceInsights?.desktop === 'failed';
	const mobileLoaded =
		typeof performanceInsights?.mobile === 'object' || performanceInsights?.mobile === 'failed';

	const isError =
		isBasicMetricsError ||
		isInsightsError ||
		isReportFailed( performanceInsights?.mobile ) ||
		isReportFailed( performanceInsights?.desktop );

	const getHashOrToken = (
		hash: string | undefined,
		token: string | undefined,
		isReportLoaded: boolean
	) => {
		if ( hash ) {
			return hash;
		} else if ( token && isReportLoaded ) {
			return token;
		}
		return '';
	};

	const testAgain = useCallback( async () => {
		setRetestState( 'queueing-advanced' );
		const result = await requeueAdvancedMetrics();
		setRetestState( 'polling-for-insights' );
		return result;
	}, [ requeueAdvancedMetrics ] );

	if (
		retestState === 'polling-for-insights' &&
		insightsStatus === 'success' &&
		( activeTab === 'mobile' ? mobileLoaded : desktopLoaded )
	) {
		setRetestState( 'idle' );
	}

	return {
		performanceReport,
		url: finalUrl ?? url,
		hash: getHashOrToken( hash, token, activeTab === 'mobile' ? mobileLoaded : desktopLoaded ),
		isLoading:
			isLoadingBasicMetrics ||
			isLoadingInsights ||
			( activeTab === 'mobile' ? ! mobileLoaded : ! desktopLoaded ),
		isError,
		isBasicMetricsFetched,
		testAgain,
		isRetesting: retestState !== 'idle',
	};
};