File size: 10,531 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { parse } from 'path';
import config from '@automattic/calypso-config';
import { WordPressLogo } from '@automattic/components';
import { isLocaleRtl } from '@automattic/i18n-utils';
import { Step } from '@automattic/onboarding';
import clsx from 'clsx';
import { Component } from 'react';
import A4ALogo from 'calypso/a8c-for-agencies/components/a4a-logo';
import EnvironmentBadge, {
	Branch,
	AccountSettingsHelper,
	AuthHelper,
	DevDocsLink,
	PreferencesHelper,
	FeaturesHelper,
	ReactQueryDevtoolsHelper,
	StoreSandboxHelper,
} from 'calypso/components/environment-badge';
import Head from 'calypso/components/head';
import JetpackLogo from 'calypso/components/jetpack-logo';
import Loading from 'calypso/components/loading';
import WooCommerceLogo from 'calypso/components/woocommerce-logo';
import isA8CForAgencies from 'calypso/lib/a8c-for-agencies/is-a8c-for-agencies';
import { isGravPoweredOAuth2Client, isWooOAuth2Client } from 'calypso/lib/oauth2-clients';
import { jsonStringifyForHtml } from 'calypso/server/sanitize';
import { initialClientsData, gravatarClientData } from 'calypso/state/oauth2-clients/reducer';
import { isBilmurEnabled, getBilmurUrl } from './utils/bilmur';
import { chunkCssLinks } from './utils/chunk';

class Document extends Component {
	render() {
		const {
			accountSettingsHelper,
			app,
			authHelper,
			badge,
			branchName,
			buildTimestamp,
			chunkFiles,
			clientData,
			commitChecksum,
			commitSha,
			devDocs,
			devDocsURL,
			entrypoint,
			env,
			featuresHelper,
			feedbackURL,
			head,
			i18nLocaleScript,
			initialQueryState,
			initialReduxState,
			inlineScriptNonce,
			isSupportSession,
			isSSP,
			lang,
			languageRevisions,
			manifests,
			params,
			preferencesHelper,
			query,
			reactQueryDevtoolsHelper,
			renderedLayout,
			sectionGroup,
			sectionName,
			storeSandboxHelper,
			target,
			user,
			useTranslationChunks,
			showStepContainerV2Loader,
		} = this.props;

		const installedChunks = entrypoint.js
			.concat( chunkFiles.js )
			.map( ( chunk ) => parse( chunk ).name );

		const inlineScript =
			`var COMMIT_SHA = ${ jsonStringifyForHtml( commitSha ) };\n` +
			`var BUILD_TIMESTAMP = ${ jsonStringifyForHtml( buildTimestamp ) };\n` +
			`var BUILD_TARGET = ${ jsonStringifyForHtml( target ) };\n` +
			( user ? `var currentUser = ${ jsonStringifyForHtml( user ) };\n` : '' ) +
			( isSupportSession ? 'var isSupportSession = true;\n' : '' ) +
			( isSSP ? 'var isSSP = true;\n' : '' ) +
			( app ? `var app = ${ jsonStringifyForHtml( app ) };\n` : '' ) +
			( initialReduxState
				? `var initialReduxState = ${ jsonStringifyForHtml( initialReduxState ) };\n`
				: '' ) +
			( initialQueryState
				? `var initialQueryState = ${ jsonStringifyForHtml( initialQueryState ) };\n`
				: '' ) +
			( clientData ? `var configData = ${ jsonStringifyForHtml( clientData ) };\n` : '' ) +
			( languageRevisions
				? `var languageRevisions = ${ jsonStringifyForHtml( languageRevisions ) };\n`
				: '' ) +
			`var installedChunks = ${ jsonStringifyForHtml( installedChunks ) };\n` +
			// Inject the locale if we can get it from the route via `getLanguageRouteParam`
			( params && params.hasOwnProperty( 'lang' )
				? `var localeFromRoute = ${ jsonStringifyForHtml( params.lang ?? '' ) };\n`
				: '' );

		const theme = config( 'theme' );

		const isRTL = isLocaleRtl( lang );

		let headTitle = head.title;
		let headFaviconUrl;
		let isWCCOM = false;

		// To customize the page title and favicon for Gravatar-related login pages.
		if ( sectionName === 'login' && typeof query?.redirect_to === 'string' ) {
			const searchParams = new URLSearchParams( query.redirect_to.split( '?' )[ 1 ] );
			// To cover the case where the `client_id` is not provided, e.g. /log-in/link/use
			const oauth2Client = initialClientsData[ searchParams.get( 'client_id' ) ] || {};

			switch ( true ) {
				case isGravPoweredOAuth2Client( oauth2Client ):
					headTitle = oauth2Client.title;
					headFaviconUrl = oauth2Client.favicon;
					break;
				case query?.gravatar_flow:
					// Use Gravatar's favicon + title for the Gravatar-related OAuth2 clients in SSR.
					headTitle = gravatarClientData.title;
					headFaviconUrl = gravatarClientData.favicon;
					break;
				case isWooOAuth2Client( oauth2Client ):
					isWCCOM = true;
					headTitle = oauth2Client.title;
					headFaviconUrl = oauth2Client.favicon;
					break;
			}
		}

		return (
			<html lang={ lang } dir={ isRTL ? 'rtl' : 'ltr' }>
				<Head
					title={ headTitle }
					branchName={ branchName }
					inlineScriptNonce={ inlineScriptNonce }
					faviconUrl={ headFaviconUrl }
				>
					{ head.metas.map( ( props, index ) => (
						<meta { ...props } key={ index } />
					) ) }
					{ head.links.map( ( props, index ) => (
						<link { ...props } key={ index } />
					) ) }
					{ chunkCssLinks( entrypoint, isRTL ) }
					{ chunkCssLinks( chunkFiles, isRTL ) }
					{ chunkFiles.js.map( ( chunk ) => (
						<link key={ chunk } rel="preload" as="script" href={ chunk } />
					) ) }
				</Head>
				<body
					className={ clsx( {
						rtl: isRTL,
						'color-scheme': config.isEnabled( 'me/account/color-scheme-picker' ),
						[ 'theme-' + theme ]: theme,
						[ 'is-group-' + sectionGroup ]: sectionGroup,
						[ 'is-section-' + sectionName ]: sectionName,
						'is-mobile-app-view': app?.isWpMobileApp || app?.isWcMobileApp,
					} ) }
				>
					{ /* eslint-disable wpcalypso/jsx-classname-namespace, react/no-danger */ }
					{ renderedLayout ? (
						<div
							id="wpcom"
							className="wpcom-site"
							data-calypso-ssr="true"
							dangerouslySetInnerHTML={ {
								__html: renderedLayout,
							} }
						/>
					) : (
						<div id="wpcom" className="wpcom-site">
							<div
								className={ clsx( 'layout', {
									[ 'is-group-' + sectionGroup ]: sectionGroup,
									[ 'is-section-' + sectionName ]: sectionName,
								} ) }
							>
								<div className="layout__content">
									<LoadingPlaceholder
										app={ app }
										sectionName={ sectionName }
										isWCCOM={ isWCCOM }
										showStepContainerV2Loader={ showStepContainerV2Loader }
									/>
								</div>
							</div>
						</div>
					) }
					{ badge && (
						<EnvironmentBadge badge={ badge } feedbackURL={ feedbackURL }>
							{ reactQueryDevtoolsHelper && <ReactQueryDevtoolsHelper /> }
							{ accountSettingsHelper && <AccountSettingsHelper /> }
							{ preferencesHelper && <PreferencesHelper /> }
							{ featuresHelper && <FeaturesHelper /> }
							{ authHelper && <AuthHelper /> }
							{ storeSandboxHelper && <StoreSandboxHelper /> }
							{ branchName && (
								<Branch branchName={ branchName } commitChecksum={ commitChecksum } />
							) }
							{ devDocs && <DevDocsLink url={ devDocsURL } /> }
						</EnvironmentBadge>
					) }

					<script
						type="text/javascript"
						nonce={ inlineScriptNonce }
						dangerouslySetInnerHTML={ {
							__html: inlineScript,
						} }
					/>
					{ i18nLocaleScript && ! useTranslationChunks && <script src={ i18nLocaleScript } /> }
					{ /*
					 * inline manifest in production, but reference by url for development.
					 * this lets us have the performance benefit in prod, without breaking HMR in dev
					 * since the manifest needs to be updated on each save
					 */ }
					{ env === 'development' && <script src={ `/calypso/${ target }/runtime.js` } /> }
					{ env !== 'development' &&
						manifests.map( ( manifest ) => (
							<script
								nonce={ inlineScriptNonce }
								dangerouslySetInnerHTML={ {
									__html: manifest,
								} }
							/>
						) ) }

					{ isBilmurEnabled() && (
						<script
							defer
							id="bilmur"
							src={ getBilmurUrl() }
							data-provider="wordpress.com"
							data-service="calypso"
							data-customproperties={ `{"route_name": "${ sectionName }"}` }
							data-site-tz="Etc/UTC"
						/>
					) }

					{ entrypoint?.language?.manifest && <script src={ entrypoint.language.manifest } /> }

					{ ( entrypoint?.language?.translations || [] ).map( ( translationChunk ) => (
						<script key={ translationChunk } src={ translationChunk } />
					) ) }

					{ entrypoint.js.map( ( asset ) => (
						<script key={ asset } src={ asset } />
					) ) }
					<script
						nonce={ inlineScriptNonce }
						dangerouslySetInnerHTML={ {
							__html: `
						 (function() {
							if ( window.console && window.configData && 'development' !== window.configData.env ) {
								console.log( "%cSTOP!", "color:#f00;font-size:xx-large" );
								console.log(
									"%cWait! This browser feature runs code that can alter your website or its security, " +
									"and is intended for developers. If you've been told to copy and paste something here " +
									"to enable a feature, someone may be trying to compromise your account. Please make " +
									"sure you understand the code and trust the source before adding anything here.",
									"font-size:large;"
								);
							}
						})();
						 `,
						} }
					/>
					<script
						nonce={ inlineScriptNonce }
						dangerouslySetInnerHTML={ {
							__html: `
							if ('serviceWorker' in navigator) {
								window.addEventListener('load', function() {
									navigator.serviceWorker.register('/service-worker.js');
								});
							}
						 `,
						} }
					/>
					<noscript className="wpcom-site__global-noscript">
						Please enable JavaScript in your browser to enjoy WordPress.com.
					</noscript>
					{ /* eslint-enable wpcalypso/jsx-classname-namespace, react/no-danger */ }
				</body>
			</html>
		);
	}
}
function LoadingPlaceholder( { app, sectionName, isWCCOM, showStepContainerV2Loader } ) {
	const shouldNotShowLoadingLogo =
		sectionName === 'checkout' || sectionName === 'stepper' || sectionName === 'signup';

	if ( shouldNotShowLoadingLogo ) {
		return showStepContainerV2Loader ? (
			<Step.Loading />
		) : (
			<Loading className="wpcom-loading__boot" />
		);
	}

	const LoadingLogo = chooseLoadingLogo( {
		isWpMobileApp: app?.isWpMobileApp,
		isWcMobileApp: app?.isWcMobileApp,
		isWCCOM,
	} );
	return <LoadingLogo size={ 72 } className="wpcom-site__logo" />;
}

function chooseLoadingLogo( { isWpMobileApp, isWcMobileApp, isWCCOM } ) {
	if ( isWcMobileApp || isWCCOM ) {
		return WooCommerceLogo;
	}

	if ( config.isEnabled( 'jetpack-cloud' ) || isWpMobileApp ) {
		return JetpackLogo;
	}

	if ( isA8CForAgencies() ) {
		return A4ALogo;
	}

	return WordPressLogo;
}

export default Document;