| 1 |
const i18n = require( '@wordpress/i18n' ); |
| 2 |
const { default: md5 } = require( 'md5-es' ); |
| 3 |
|
| 4 |
const locationMap = { |
| 5 |
plugin: 'plugins/', |
| 6 |
theme: 'themes/', |
| 7 |
core: '', |
| 8 |
}; |
| 9 |
|
| 10 |
const hasOwn = ( obj, prop ) => Object.prototype.hasOwnProperty.call( obj, prop ); |
| 11 |
|
| 12 |
module.exports = { |
| 13 |
state: { |
| 14 |
baseUrl: null, |
| 15 |
locale: null, |
| 16 |
domainMap: {}, |
| 17 |
domainPaths: {}, |
| 18 |
}, |
| 19 |
|
| 20 |
/** |
| 21 |
* Download and register translations for a bundle. |
| 22 |
* |
| 23 |
* @param {string} path - Bundle path being fetched. May have a query part. |
| 24 |
* @param {string} domain - Text domain to register into. |
| 25 |
* @param {string} location - Location for the translation: 'plugin', 'theme', or 'core'. |
| 26 |
* @return {Promise} Resolved when the translations are registered, or rejected with an `Error`. |
| 27 |
*/ |
| 28 |
async downloadI18n( path, domain, location ) { |
| 29 |
const state = this.state; |
| 30 |
if ( ! state || typeof state.baseUrl !== 'string' ) { |
| 31 |
throw new Error( 'wp.jpI18nLoader.state is not set' ); |
| 32 |
} |
| 33 |
|
| 34 |
// "en_US" is the default, no translations are needed. |
| 35 |
if ( state.locale === 'en_US' ) { |
| 36 |
return; |
| 37 |
} |
| 38 |
|
| 39 |
// Check that fetch is available. |
| 40 |
if ( typeof fetch === 'undefined' ) { |
| 41 |
throw new Error( 'Fetch API is not available.' ); |
| 42 |
} |
| 43 |
|
| 44 |
// Extract any query part and hash the script name like WordPress does. |
| 45 |
const pathPrefix = hasOwn( state.domainPaths, domain ) ? state.domainPaths[ domain ] : ''; |
| 46 |
let hash, query; |
| 47 |
const i = path.indexOf( '?' ); |
| 48 |
if ( i >= 0 ) { |
| 49 |
hash = md5.hash( pathPrefix + path.substring( 0, i ) ); |
| 50 |
query = path.substring( i ); |
| 51 |
} else { |
| 52 |
hash = md5.hash( pathPrefix + path ); |
| 53 |
query = ''; |
| 54 |
} |
| 55 |
|
| 56 |
// Download. |
| 57 |
const locationAndDomain = hasOwn( state.domainMap, domain ) |
| 58 |
? state.domainMap[ domain ] |
| 59 |
: locationMap[ location ] + domain; |
| 60 |
const res = await fetch( |
| 61 |
// prettier-ignore |
| 62 |
`${ state.baseUrl }${ locationAndDomain }-${ state.locale }-${ hash }.json${ query }` |
| 63 |
); |
| 64 |
if ( ! res.ok ) { |
| 65 |
throw new Error( `HTTP request failed: ${ res.status } ${ res.statusText }` ); |
| 66 |
} |
| 67 |
const data = await res.json(); |
| 68 |
|
| 69 |
// Extract the messages from the file and register them. |
| 70 |
const localeData = hasOwn( data.locale_data, domain ) |
| 71 |
? data.locale_data[ domain ] |
| 72 |
: data.locale_data.messages; |
| 73 |
localeData[ '' ].domain = domain; |
| 74 |
i18n.setLocaleData( localeData, domain ); |
| 75 |
}, |
| 76 |
}; |
| 77 |
|