From 64bda6f98267a79a719fccd44d7b0e1eb5dc7c0d Mon Sep 17 00:00:00 2001 From: Robbie Antenesse Date: Mon, 9 Sep 2019 16:19:39 -0600 Subject: [PATCH] Set up custom i18n implementation --- app/i18n/index.js | 39 +++++++++++++++++++++++++++++++++++++++ app/i18n/locales/en.json | 17 +++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 app/i18n/index.js create mode 100644 app/i18n/locales/en.json diff --git a/app/i18n/index.js b/app/i18n/index.js new file mode 100644 index 0000000..573f31b --- /dev/null +++ b/app/i18n/index.js @@ -0,0 +1,39 @@ +import en from './locales/en.json'; + +export class I18n { + constructor(appState) { + // Available languages should be kept up to date with the available locales. + this.availableLanguages = { + default: en, + en, + }; + this.language = appState.language; + } + + translate (section, phrase) { + let result; + let language = this.availableLanguages.default; + + if (typeof this.availableLanguages[this.language] == 'undefined') { + console.warn(`The target language (${this.language}) does not exist. Defaulting to ${this.availableLanguages.default.name} (${this.availableLanguages.default.locale}).`); + } else if (typeof this.availableLanguages[this.language][section] == 'undefined' || typeof this.availableLanguages[this.language][section][phrase] == 'undefined') { + console.warn(`The translation for "${section}.${phrase}" is not set in the ${this.language} locale. Using ${this.availableLanguages.default.name} (${this.availableLanguages.default.locale}) instead.`); + } else { + language = this.availableLanguages[this.language]; + } + + if (typeof language[section] !== 'undefined' && typeof language[section][phrase] !== 'undefined') { + result = language[section][phrase]; + } else { + console.error(`The translation for "${section}.${phrase}" is set up in neither the target nor default locale.`); + } + + return result; + } + + __ (translation) { + const pieces = translation.split('.'); + const result = this.translate(pieces[0], pieces[1]); + return result; + } +} diff --git a/app/i18n/locales/en.json b/app/i18n/locales/en.json new file mode 100644 index 0000000..19e749c --- /dev/null +++ b/app/i18n/locales/en.json @@ -0,0 +1,17 @@ +{ + "name": "English", + "locale": "en", + "home": { + "subtitle": "An attempt at a viable alternative to Goodreads", + "temp_left": "Still gotta figure out a design.", + "temp_right": "It's early days, my friends!" + }, + "login": { + "email": "Email", + "password": "Password", + "login_button": "Log In!" + }, + "search": { + "header": "Search" + } +} \ No newline at end of file