File size: 2,042 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 { useEffect, useState } from '@wordpress/element';
import { useTranslate } from 'i18n-calypso';
import Notice from 'calypso/components/notice';
import wpcom from 'calypso/lib/wp';

/**
 * We make a separate request rather than using getSite here to
 * avoid querying the WP.com cache of a site, which returns theme
 * errors for the multisite (caused by its 'force=wpcom' param).
 * Also, `theme_errors` is an expensive field that is not normally
 * fetched by the common `QuerySite` or `QuerySites` helpers.
 */
function fetchSiteThemeErrorsWithoutForceWpcom( siteId ) {
	return wpcom.req.get( {
		path: '/sites/' + encodeURIComponent( siteId ),
		apiVersion: '1.1',
		query: {
			fields: 'ID,options',
			options: 'theme_errors',
		},
	} );
}

const ThemeErrors = ( { siteId } ) => {
	const translate = useTranslate();
	const [ themeErrors, setThemeErrors ] = useState( [] );

	useEffect( () => {
		fetchSiteThemeErrorsWithoutForceWpcom( siteId ).then( ( siteData ) => {
			const errors = siteData?.options?.theme_errors;
			setThemeErrors( errors || [] );
		} );
	}, [ siteId ] );

	const dismissNotice = ( themeName, errorIndex ) => {
		setThemeErrors( ( prevErrors ) =>
			prevErrors
				.map( ( theme ) =>
					theme.name === themeName
						? {
								...theme,
								errors: theme.errors.filter( ( _, index ) => index !== errorIndex ),
						  }
						: theme
				)
				.filter( ( theme ) => theme.errors.length > 0 )
		);
	};

	if ( themeErrors.length === 0 ) {
		return null;
	}

	return (
		<>
			{ themeErrors.map( ( theme ) =>
				theme.errors.map( ( error, index ) => (
					<Notice
						status="is-error"
						key={ index }
						onDismissClick={ () => dismissNotice( theme.name, index ) }
					>
						{ translate( 'Error with theme {{strong}}%(themeName)s{{/strong}}: %(themeError)s', {
							args: {
								themeName: theme.name,
								themeError: error,
							},
							components: {
								strong: <strong />,
							},
						} ) }
					</Notice>
				) )
			) }
		</>
	);
};

export default ThemeErrors;