| import config from '@automattic/calypso-config'; |
| import { captureException } from '@automattic/calypso-sentry'; |
| import { getUrlFromParts, getUrlParts } from '@automattic/calypso-url'; |
| import { isDefaultLocale, getLanguage } from '@automattic/i18n-utils'; |
| import { setLocale as setLocaleNumberFormatters } from '@automattic/number-formatters'; |
| import debugFactory from 'debug'; |
| import i18n from 'i18n-calypso'; |
| import { forEach, throttle } from 'lodash'; |
| const debug = debugFactory( 'calypso:i18n' ); |
|
|
| const getPromises = {}; |
|
|
| |
| |
| |
| |
| |
| |
| function dedupedGet( url ) { |
| if ( ! ( url in getPromises ) ) { |
| getPromises[ url ] = globalThis.fetch( url ).finally( () => delete getPromises[ url ] ); |
| } |
|
|
| return getPromises[ url ]; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| export function getLanguageFilePathUrl() { |
| const protocol = typeof window === 'undefined' ? 'https://' : '//'; |
|
|
| return `${ protocol }widgets.wp.com/languages/calypso/`; |
| } |
|
|
| |
| |
| |
| |
| export function getLanguagesInternalBasePath() { |
| return `/calypso/languages`; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| export function getLanguageFileUrl( localeSlug, fileType = 'json', languageRevisions = {} ) { |
| if ( ! [ 'js', 'json' ].includes( fileType ) ) { |
| fileType = 'json'; |
| } |
|
|
| const fileUrl = `${ getLanguageFilePathUrl() }${ localeSlug }-v1.1.${ fileType }`; |
| let revision = languageRevisions[ localeSlug ]; |
|
|
| if ( typeof revision === 'number' ) { |
| revision = revision.toString(); |
| } |
|
|
| return typeof revision === 'string' ? fileUrl + `?v=${ revision }` : fileUrl; |
| } |
|
|
| function getHtmlLangAttribute() { |
| |
| const slug = i18n.translate( 'html_lang_attribute' ); |
|
|
| |
| |
| |
| if ( slug === 'html_lang_attribute' ) { |
| return i18n.getLocaleSlug(); |
| } |
|
|
| return slug; |
| } |
|
|
| function setLocaleInDOM() { |
| const htmlLangAttribute = getHtmlLangAttribute(); |
| const isRTL = i18n.isRtl(); |
| document.documentElement.lang = htmlLangAttribute; |
| document.documentElement.dir = isRTL ? 'rtl' : 'ltr'; |
| document.body.classList[ isRTL ? 'add' : 'remove' ]( 'rtl' ); |
|
|
| switchWebpackCSS( isRTL ); |
| } |
|
|
| export async function getFile( url ) { |
| const response = await dedupedGet( url ); |
| if ( response.ok ) { |
| if ( response.bodyUsed ) { |
| |
| |
| |
| return; |
| } |
| return await response.json(); |
| } |
|
|
| |
| throw new Error(); |
| } |
|
|
| export function getLanguageFile( targetLocaleSlug ) { |
| const languageRevisions = typeof window !== 'undefined' ? window.languageRevisions : {}; |
| const url = getLanguageFileUrl( targetLocaleSlug, 'json', languageRevisions ); |
|
|
| return getFile( url ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| export function getLanguageManifestFileUrl( { localeSlug, fileType = 'json', hash = null } = {} ) { |
| if ( ! [ 'js', 'json' ].includes( fileType ) ) { |
| fileType = 'json'; |
| } |
|
|
| if ( typeof hash === 'number' ) { |
| hash = hash.toString(); |
| } |
|
|
| const fileBasePath = getLanguagesInternalBasePath(); |
| const fileUrl = `${ fileBasePath }/${ localeSlug }-language-manifest.${ fileType }`; |
|
|
| return typeof hash === 'string' ? fileUrl + `?v=${ hash }` : fileUrl; |
| } |
|
|
| |
| |
| |
| |
| |
| function getIsLanguageManifestPreloaded( localeSlug ) { |
| return ( |
| window?.i18nLanguageManifest && |
| window?.i18nLanguageManifest?.locale?.[ '' ]?.localeSlug === localeSlug |
| ); |
| } |
|
|
| |
| |
| |
| |
| |
| export function getLanguageManifestFile( localeSlug ) { |
| if ( getIsLanguageManifestPreloaded( localeSlug ) ) { |
| return window.i18nLanguageManifest; |
| } |
|
|
| const url = getLanguageManifestFileUrl( { |
| localeSlug, |
| fileType: 'json', |
| hash: window?.languageRevisions?.hashes?.[ localeSlug ] || null, |
| } ); |
|
|
| return getFile( url ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export function getTranslationChunkFileUrl( { |
| chunkId, |
| localeSlug, |
| fileType = 'json', |
| hash = null, |
| } = {} ) { |
| if ( ! [ 'js', 'json' ].includes( fileType ) ) { |
| fileType = 'json'; |
| } |
|
|
| if ( typeof hash === 'number' ) { |
| hash = hash.toString(); |
| } |
|
|
| const fileBasePath = getLanguagesInternalBasePath(); |
| const fileName = `${ localeSlug }-${ chunkId }.${ fileType }`; |
| const fileUrl = `${ fileBasePath }/${ fileName }`; |
|
|
| return typeof hash === 'string' ? fileUrl + `?v=${ hash }` : fileUrl; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function getIsTranslationChunkPreloaded( chunkId, localeSlug ) { |
| if ( typeof window !== 'undefined' ) { |
| return ( |
| window.i18nLanguageManifest?.locale?.[ '' ]?.localeSlug === localeSlug && |
| window.i18nTranslationChunks && |
| chunkId in window.i18nTranslationChunks |
| ); |
| } |
| return false; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| export function getTranslationChunkFile( chunkId, localeSlug ) { |
| if ( getIsTranslationChunkPreloaded( chunkId, localeSlug ) ) { |
| return Promise.resolve( window.i18nTranslationChunks[ chunkId ] ); |
| } |
|
|
| const url = getTranslationChunkFileUrl( { |
| chunkId, |
| localeSlug, |
| fileType: 'json', |
| hash: window?.languageRevisions?.[ localeSlug ] || null, |
| } ); |
|
|
| return getFile( url ); |
| } |
|
|
| |
| |
| |
| |
| |
| function getInstalledChunks() { |
| const installedChunksFromContext = window.installedChunks ?? []; |
| const installedChunksAsync = window?.__requireChunkCallback__?.getInstalledChunks?.() ?? []; |
| const installedChunksSet = new Set( |
| [].concat( installedChunksFromContext, installedChunksAsync ) |
| ); |
|
|
| return Array.from( installedChunksSet ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| function captureGetTranslationChunkFileException( error, chunkId, localeSlug ) { |
| captureException( error, { |
| tags: { |
| chunk_id: chunkId, |
| locale_slug: localeSlug, |
| }, |
| } ); |
| } |
|
|
| |
| |
| |
| let lastRequireChunkTranslationsHandler = null; |
|
|
| |
| |
| |
| |
| |
| |
| |
| function addRequireChunkTranslationsHandler( localeSlug = i18n.getLocaleSlug(), options = {} ) { |
| const { translatedChunks = [], userTranslations = {} } = options; |
| const loadedTranslationChunks = {}; |
|
|
| const handler = ( { scriptSrc, publicPath }, promises ) => { |
| const chunkId = scriptSrc.replace( publicPath, '' ).replace( /\.js$/, '' ); |
|
|
| if ( ! translatedChunks.includes( chunkId ) || loadedTranslationChunks[ chunkId ] ) { |
| return; |
| } |
|
|
| const translationChunkPromise = getTranslationChunkFile( chunkId, localeSlug ) |
| .then( ( translations ) => { |
| addTranslations( translations, userTranslations ); |
| loadedTranslationChunks[ chunkId ] = true; |
| } ) |
| .catch( ( cause ) => { |
| const error = new Error( |
| `Encountered an error loading translation chunk in require chunk translations handler.`, |
| { cause } |
| ); |
| |
| |
| debug( error ); |
| } ); |
|
|
| promises.push( translationChunkPromise ); |
| }; |
|
|
| window?.__requireChunkCallback__?.add?.( handler ); |
| lastRequireChunkTranslationsHandler = handler; |
| } |
|
|
| |
| |
| |
| function removeRequireChunkTranslationsHandler() { |
| window?.__requireChunkCallback__?.remove?.( lastRequireChunkTranslationsHandler ); |
| } |
|
|
| let lastRequestedLocale = null; |
| export default async function switchLocale( localeSlug ) { |
| |
| const language = getLanguage( localeSlug ); |
|
|
| if ( ! language ) { |
| return; |
| } |
|
|
| |
| |
| if ( typeof document === 'undefined' ) { |
| return; |
| } |
|
|
| |
| setLocaleNumberFormatters( localeSlug ); |
|
|
| lastRequestedLocale = localeSlug; |
|
|
| const useTranslationChunks = |
| config.isEnabled( 'use-translation-chunks' ) || |
| getUrlParts( document.location.href ).searchParams.has( 'useTranslationChunks' ); |
|
|
| if ( isDefaultLocale( localeSlug ) ) { |
| i18n.configure( { defaultLocaleSlug: localeSlug } ); |
| setLocaleInDOM(); |
| } else if ( useTranslationChunks ) { |
| |
| |
| if ( localeSlug === i18n.getLocaleSlug() ) { |
| setLocaleInDOM(); |
| return; |
| } |
|
|
| |
| |
| |
| try { |
| const languageManifest = getLanguageManifestFile( localeSlug ); |
| const { translatedChunks, locale } = |
| ( languageManifest instanceof Promise ? await languageManifest : languageManifest ) ?? {}; |
|
|
| if ( ! locale || ! translatedChunks ) { |
| return; |
| } |
|
|
| i18n.setLocale( locale ); |
| setLocaleInDOM(); |
| removeRequireChunkTranslationsHandler(); |
| addRequireChunkTranslationsHandler( localeSlug, { translatedChunks } ); |
|
|
| const translatedInstalledChunks = getInstalledChunks().filter( ( chunkId ) => |
| translatedChunks.includes( chunkId ) |
| ); |
| const preloadedTranslatedInstalledChunks = translatedInstalledChunks.filter( ( chunkId ) => |
| getIsTranslationChunkPreloaded( chunkId, localeSlug ) |
| ); |
| const translatedInstalledChunksToBeLoaded = translatedInstalledChunks.filter( |
| ( chunkId ) => ! getIsTranslationChunkPreloaded( chunkId, localeSlug ) |
| ); |
|
|
| |
| const preloadedTranslations = preloadedTranslatedInstalledChunks.reduce( |
| ( acc, chunkId ) => Object.assign( acc, window.i18nTranslationChunks?.[ chunkId ] ), |
| {} |
| ); |
| addTranslations( preloadedTranslations ); |
|
|
| |
| translatedInstalledChunksToBeLoaded.forEach( ( chunkId ) => |
| getTranslationChunkFile( chunkId, localeSlug ) |
| .then( ( translations ) => addTranslations( translations ) ) |
| .catch( ( cause ) => { |
| const error = new Error( |
| `Encountered an error loading translation chunk while switching the locale.`, |
| { cause } |
| ); |
| |
| |
| debug( error ); |
| } ) |
| ); |
|
|
| const userTranslations = await loadUserUndeployedTranslations( localeSlug ); |
|
|
| |
| if ( userTranslations ) { |
| removeRequireChunkTranslationsHandler(); |
| addRequireChunkTranslationsHandler( localeSlug, { |
| translatedChunks, |
| userTranslations, |
| } ); |
| } |
| } catch ( error ) { |
| debug( |
| `Encountered an error loading language manifest and/or translation chunks for ${ localeSlug }. Falling back to English.` |
| ); |
| debug( error ); |
| } |
| } else { |
| getLanguageFile( localeSlug ).then( |
| |
| ( body ) => { |
| if ( body ) { |
| |
| |
| if ( localeSlug !== lastRequestedLocale ) { |
| return; |
| } |
|
|
| i18n.setLocale( body ); |
| setLocaleInDOM(); |
| loadUserUndeployedTranslations( localeSlug ); |
| } |
| }, |
| |
| () => { |
| debug( |
| `Encountered an error loading locale file for ${ localeSlug }. Falling back to English.` |
| ); |
| } |
| ); |
| } |
| } |
|
|
| export function loadUserUndeployedTranslations( currentLocaleSlug ) { |
| if ( typeof window === 'undefined' || ! window.location || ! window.location.search ) { |
| return; |
| } |
|
|
| const search = new URLSearchParams( window.location.search ); |
| const params = Object.fromEntries( search.entries() ); |
|
|
| const { |
| 'load-user-translations': username, |
| project = 'wpcom', |
| translationSet = 'default', |
| translationStatus = 'current', |
| locale = currentLocaleSlug, |
| } = params; |
|
|
| if ( ! username ) { |
| return; |
| } |
|
|
| if ( ! [ 'current', 'waiting' ].includes( translationStatus ) ) { |
| return; |
| } |
|
|
| if ( 'waiting' === translationStatus ) { |
| |
| return; |
| } |
|
|
| const pathname = [ |
| 'api', |
| 'projects', |
| project, |
| locale, |
| translationSet, |
| 'export-translations', |
| ].join( '/' ); |
|
|
| const searchParams = new URLSearchParams( { |
| 'filters[user_login]': username, |
| 'filters[status]': translationStatus, |
| format: 'json', |
| } ); |
|
|
| const requestUrl = getUrlFromParts( { |
| protocol: 'https:', |
| host: 'translate.wordpress.com', |
| pathname, |
| searchParams, |
| } ); |
|
|
| return window |
| .fetch( requestUrl.href, { |
| headers: { Accept: 'application/json' }, |
| credentials: 'include', |
| } ) |
| .then( ( res ) => res.json() ) |
| .then( ( translations ) => { |
| addTranslations( translations ); |
|
|
| return translations; |
| } ); |
| } |
|
|
| |
| |
| |
| |
| |
| function setRTLFlagOnCSSLink( url, isRTL ) { |
| if ( isRTL ) { |
| return url.endsWith( '.rtl.css' ) ? url : url.replace( /\.css$/, '.rtl.css' ); |
| } |
|
|
| return ! url.endsWith( '.rtl.css' ) ? url : url.replace( /\.rtl.css$/, '.css' ); |
| } |
|
|
| |
| |
| |
| |
| export function switchWebpackCSS( isRTL ) { |
| const currentLinks = document.querySelectorAll( 'link[rel="stylesheet"][data-webpack]' ); |
|
|
| forEach( currentLinks, async ( currentLink ) => { |
| const currentHref = currentLink.getAttribute( 'href' ); |
| const newHref = setRTLFlagOnCSSLink( currentHref, isRTL ); |
| const isNewHrefAdded = currentLink.parentElement?.querySelector( `[href = '${ newHref }']` ); |
|
|
| if ( currentHref === newHref || isNewHrefAdded ) { |
| return; |
| } |
|
|
| const newLink = await loadCSS( newHref, currentLink ); |
|
|
| if ( newLink ) { |
| newLink.setAttribute( 'data-webpack', true ); |
| currentLink.parentElement?.removeChild( currentLink ); |
| } |
| } ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function loadCSS( cssUrl, currentLink ) { |
| return new Promise( ( resolve ) => { |
| |
| |
| const isRTL = i18n.isRtl(); |
| const isRTLHref = currentLink.getAttribute( 'href' ).endsWith( '.rtl.css' ); |
|
|
| if ( isRTL === isRTLHref ) { |
| return resolve( null ); |
| } |
|
|
| const link = document.createElement( 'link' ); |
| link.rel = 'stylesheet'; |
| link.type = 'text/css'; |
| link.href = cssUrl; |
|
|
| if ( 'onload' in link ) { |
| link.onload = () => { |
| link.onload = null; |
| resolve( link ); |
| }; |
| } else { |
| |
| |
| |
| setTimeout( () => resolve( link ), 500 ); |
| } |
|
|
| document.head.insertBefore( link, currentLink ? currentLink.nextSibling : null ); |
| } ); |
| } |
|
|
| |
| |
| |
| |
| const _translationsBatch = []; |
|
|
| |
| |
| |
| |
| |
| |
| const _addTranslationsBatch = throttle( function ( userTranslations ) { |
| window.performance?.mark?.( 'add_translations_start' ); |
| i18n.addTranslations( Object.assign( {}, ..._translationsBatch.splice( 0 ), userTranslations ) ); |
| window.performance?.measure?.( 'add_translations', 'add_translations_start' ); |
| window.performance?.clearMarks?.( 'add_translations_start' ); |
| }, 50 ); |
|
|
| |
| |
| |
| |
| |
| function addTranslations( translations, userTranslations ) { |
| _translationsBatch.push( translations ); |
| _addTranslationsBatch( userTranslations ); |
| } |
|
|