File size: 2,725 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 |
import debugFactory from 'debug';
import i18n from 'i18n-calypso';
import moment from 'moment';
const debug = debugFactory( 'apps:advertising' );
const DEFAULT_LANGUAGE = 'en';
const DEFAULT_MOMENT_LOCALE = 'en';
const ALWAYS_LOAD_WITH_LOCALE = [ 'zh' ];
const getLanguageCodeFromLocale = ( localeSlug ) => {
if ( localeSlug.indexOf( '-' ) > -1 ) {
return localeSlug.split( '-' )[ 0 ];
}
return localeSlug;
};
const loadMomentLocale = ( localeSlug, languageCode ) => {
return import( `moment/locale/${ localeSlug }` )
.catch( ( error ) => {
debug(
`Encountered an error loading moment locale file for ${ localeSlug }. Falling back to language datetime format.`,
error
);
// Fallback 1 to the language code.
if ( localeSlug !== languageCode ) {
localeSlug = languageCode;
return import( `moment/locale/${ localeSlug }` );
}
// Pass it to the next catch block if the language code is the same as the locale slug.
return Promise.reject( error );
} )
.catch( ( error ) => {
debug(
`Encountered an error loading moment locale file for ${ localeSlug }. Falling back to US datetime format.`,
error
);
// Fallback 2 to the default US date time format.
// Interestingly `en` here represents `en-us` locale.
localeSlug = DEFAULT_MOMENT_LOCALE;
} )
.then( () => moment.locale( localeSlug ) );
};
const loadLanguageFile = ( languageFileName ) => {
const url = `https://widgets.wp.com/blaze-dashboard/v1/languages/${ languageFileName }-v1.1.json`;
return globalThis.fetch( url ).then( ( response ) => {
if ( response.ok ) {
return response.json().then( ( body ) => {
if ( body ) {
i18n.setLocale( body );
}
} );
}
return Promise.reject( response );
} );
};
export default ( localeSlug ) => {
const languageCode = getLanguageCodeFromLocale( localeSlug );
// Load translation file if it's not English.
if ( languageCode !== DEFAULT_LANGUAGE ) {
const languageFileName = ALWAYS_LOAD_WITH_LOCALE.includes( languageCode )
? localeSlug
: languageCode;
// We don't have to wait for the language file to load before rendering the page, because i18n is using hooks to update translations.
loadLanguageFile( languageFileName )
.then( () => debug( `Loaded locale files for ${ languageCode } successfully.` ) )
.catch( ( error ) =>
debug(
`Encountered an error loading locale file for ${ languageCode }. Falling back to English.`,
error
)
);
}
// We have to wait for moment locale to load before rendering the page, because otherwise the rendered date time wouldn't get re-rendered.
// This could be improved in the future with hooks.
return loadMomentLocale( localeSlug, languageCode );
};
|