File size: 2,312 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
import config from '@automattic/calypso-config';
import { localizeUrl, getLanguageSlugs } from '@automattic/i18n-utils';
import performanceMark from 'calypso/server/lib/performance-mark';
import { isUserLoggedIn } from 'calypso/state/current-user/selectors';
import { setDocumentHeadLink } from 'calypso/state/document-head/actions';

const getLocalizedCanonicalUrl = ( path, locale, excludeSearch = false ) => {
	const baseUrl = new URL( path, 'https://wordpress.com' );

	if ( excludeSearch ) {
		baseUrl.search = '';
	}

	const baseUrlWithoutLang = baseUrl.href.replace(
		new RegExp( `\\/(${ getLanguageSlugs().join( '|' ) })(\\/|\\?|$)` ),
		'$2'
	);
	let localizedUrl = localizeUrl( baseUrlWithoutLang, locale, false );

	// Remove the trailing slash if `path` doesn't have one either.
	if ( ! path.endsWith( '/' ) && localizedUrl.endsWith( '/' ) ) {
		localizedUrl = localizedUrl.slice( 0, -1 );
	}

	return localizedUrl;
};

export const excludeSearchFromCanonicalUrlAndHrefLangLinks = ( context, next ) => {
	context.excludeSearchFromCanonicalUrl = true;
	next();
};

export const setLocalizedCanonicalUrl = ( context, next ) => {
	performanceMark( context, 'setLocalizedCanonicalUrl' );

	if ( ! context.isServerSide || isUserLoggedIn( context.store.getState() ) ) {
		next();
		return;
	}

	const canonicalUrl = getLocalizedCanonicalUrl(
		context.originalUrl,
		context.i18n.getLocaleSlug(),
		context.excludeSearchFromCanonicalUrl
	);

	context.store.dispatch(
		setDocumentHeadLink( {
			rel: 'canonical',
			href: canonicalUrl,
		} )
	);

	next();
};

export const setHrefLangLinks = ( context, next ) => {
	if ( ! context.isServerSide || isUserLoggedIn( context.store.getState() ) ) {
		next();
		return;
	}
	performanceMark( context, 'setHrefLangLinks' );

	const langCodes = [ 'x-default', 'en', ...config( 'magnificent_non_en_locales' ) ];
	const hrefLangBlock = langCodes.map( ( hrefLang ) => {
		let localeSlug = hrefLang;

		if ( localeSlug === 'x-default' ) {
			localeSlug = config( 'i18n_default_locale_slug' );
		}

		const href = getLocalizedCanonicalUrl(
			context.originalUrl,
			localeSlug,
			context.excludeSearchFromCanonicalUrl
		);

		return {
			rel: 'alternate',
			hrefLang,
			href,
		};
	} );

	context.store.dispatch( setDocumentHeadLink( hrefLangBlock ) );
	next();
};