2017-05-23 14:16:31 +00:00
|
|
|
/*
|
|
|
|
Copyright 2017 MTRNord and Cooperative EITA
|
2017-05-25 10:24:17 +00:00
|
|
|
Copyright 2017 Vector Creations Ltd.
|
2017-05-23 14:16:31 +00:00
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
|
|
|
import request from 'browser-request';
|
2017-05-25 10:24:17 +00:00
|
|
|
import counterpart from 'counterpart';
|
2017-07-12 12:58:14 +00:00
|
|
|
import Promise from 'bluebird';
|
2017-06-12 15:45:36 +00:00
|
|
|
import React from 'react';
|
2017-10-29 22:53:00 +00:00
|
|
|
import SettingsStore from "./settings/SettingsStore";
|
2017-05-25 10:24:17 +00:00
|
|
|
|
2017-05-23 14:16:31 +00:00
|
|
|
const i18nFolder = 'i18n/';
|
|
|
|
|
2017-05-25 10:24:17 +00:00
|
|
|
// We use english strings as keys, some of which contain full stops
|
|
|
|
counterpart.setSeparator('|');
|
|
|
|
// Fall back to English
|
|
|
|
counterpart.setFallbackLocale('en');
|
|
|
|
|
2017-09-22 19:43:27 +00:00
|
|
|
// Function which only purpose is to mark that a string is translatable
|
|
|
|
// Does not actually do anything. It's helpful for automatic extraction of translatable strings
|
|
|
|
export function _td(s) {
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
2017-05-25 10:24:17 +00:00
|
|
|
// The translation function. This is just a simple wrapper to counterpart,
|
|
|
|
// but exists mostly because we must use the same counterpart instance
|
|
|
|
// between modules (ie. here (react-sdk) and the app (riot-web), and if we
|
|
|
|
// just import counterpart and use it directly, we end up using a different
|
|
|
|
// instance.
|
|
|
|
export function _t(...args) {
|
2017-06-06 12:56:37 +00:00
|
|
|
// Horrible hack to avoid https://github.com/vector-im/riot-web/issues/4191
|
|
|
|
// The interpolation library that counterpart uses does not support undefined/null
|
|
|
|
// values and instead will throw an error. This is a problem since everywhere else
|
|
|
|
// in JS land passing undefined/null will simply stringify instead, and when converting
|
|
|
|
// valid ES6 template strings to i18n strings it's extremely easy to pass undefined/null
|
|
|
|
// if there are no existing null guards. To avoid this making the app completely inoperable,
|
|
|
|
// we'll check all the values for undefined/null and stringify them here.
|
|
|
|
if (args[1] && typeof args[1] === 'object') {
|
|
|
|
Object.keys(args[1]).forEach((k) => {
|
|
|
|
if (args[1][k] === undefined) {
|
|
|
|
console.warn("_t called with undefined interpolation name: " + k);
|
|
|
|
args[1][k] = 'undefined';
|
|
|
|
}
|
|
|
|
if (args[1][k] === null) {
|
|
|
|
console.warn("_t called with null interpolation name: " + k);
|
|
|
|
args[1][k] = 'null';
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2017-05-25 10:24:17 +00:00
|
|
|
return counterpart.translate(...args);
|
|
|
|
}
|
|
|
|
|
2017-05-30 14:55:21 +00:00
|
|
|
/*
|
|
|
|
* Translates stringified JSX into translated JSX. E.g
|
|
|
|
* _tJsx(
|
|
|
|
* "click <a href=''>here</a> now",
|
|
|
|
* /<a href=''>(.*?)<\/a>/,
|
|
|
|
* (sub) => { return <a href=''>{ sub }</a>; }
|
|
|
|
* );
|
|
|
|
*
|
|
|
|
* @param {string} jsxText The untranslated stringified JSX e.g "click <a href=''>here</a> now".
|
|
|
|
* This will be translated by passing the string through to _t(...)
|
|
|
|
*
|
2017-05-30 15:17:42 +00:00
|
|
|
* @param {RegExp|RegExp[]} patterns A regexp to match against the translated text.
|
2017-05-30 14:55:21 +00:00
|
|
|
* The captured groups from the regexp will be fed to 'sub'.
|
|
|
|
* Only the captured groups will be included in the output, the match itself is discarded.
|
2017-05-30 15:17:42 +00:00
|
|
|
* If multiple RegExps are provided, the function at the same position will be called. The
|
|
|
|
* match will always be done from left to right, so the 2nd RegExp will be matched against the
|
|
|
|
* remaining text from the first RegExp.
|
2017-05-30 14:55:21 +00:00
|
|
|
*
|
2017-05-30 15:17:42 +00:00
|
|
|
* @param {Function|Function[]} subs A function which will be called
|
2017-05-30 14:55:21 +00:00
|
|
|
* with multiple args, each arg representing a captured group of the matching regexp.
|
|
|
|
* This function must return a JSX node.
|
|
|
|
*
|
2017-06-12 15:45:36 +00:00
|
|
|
* @return a React <span> component containing the generated text
|
2017-05-30 14:55:21 +00:00
|
|
|
*/
|
2017-05-30 15:17:42 +00:00
|
|
|
export function _tJsx(jsxText, patterns, subs) {
|
|
|
|
// convert everything to arrays
|
|
|
|
if (patterns instanceof RegExp) {
|
|
|
|
patterns = [patterns];
|
2017-05-30 14:55:21 +00:00
|
|
|
}
|
2017-05-30 15:17:42 +00:00
|
|
|
if (subs instanceof Function) {
|
|
|
|
subs = [subs];
|
|
|
|
}
|
|
|
|
// sanity checks
|
|
|
|
if (subs.length !== patterns.length || subs.length < 1) {
|
|
|
|
throw new Error(`_tJsx: programmer error. expected number of RegExps == number of Functions: ${subs.length} != ${patterns.length}`);
|
|
|
|
}
|
|
|
|
for (let i = 0; i < subs.length; i++) {
|
2017-10-11 16:56:17 +00:00
|
|
|
if (!(patterns[i] instanceof RegExp)) {
|
2017-05-30 15:17:42 +00:00
|
|
|
throw new Error(`_tJsx: programmer error. expected RegExp for text: ${jsxText}`);
|
|
|
|
}
|
2017-10-11 16:56:17 +00:00
|
|
|
if (!(subs[i] instanceof Function)) {
|
2017-05-30 15:17:42 +00:00
|
|
|
throw new Error(`_tJsx: programmer error. expected Function for text: ${jsxText}`);
|
|
|
|
}
|
2017-05-30 14:55:21 +00:00
|
|
|
}
|
|
|
|
|
2017-05-31 08:29:43 +00:00
|
|
|
// The translation returns text so there's no XSS vector here (no unsafe HTML, no code execution)
|
2017-10-11 07:14:11 +00:00
|
|
|
const tJsxText = _t(jsxText, {interpolate: false});
|
2017-10-11 16:56:17 +00:00
|
|
|
const output = [tJsxText];
|
2017-10-11 18:02:14 +00:00
|
|
|
|
2017-05-30 15:17:42 +00:00
|
|
|
for (let i = 0; i < patterns.length; i++) {
|
|
|
|
// convert the last element in 'output' into 3 elements (pre-text, sub function, post-text).
|
|
|
|
// Rinse and repeat for other patterns (using post-text).
|
2017-10-11 16:56:17 +00:00
|
|
|
const inputText = output.pop();
|
|
|
|
const match = inputText.match(patterns[i]);
|
2017-05-30 15:17:42 +00:00
|
|
|
if (!match) {
|
|
|
|
throw new Error(`_tJsx: translator error. expected translation to match regexp: ${patterns[i]}`);
|
|
|
|
}
|
2017-10-11 16:56:17 +00:00
|
|
|
const capturedGroups = match.slice(1);
|
2017-05-30 15:17:42 +00:00
|
|
|
|
|
|
|
// Return the raw translation before the *match* followed by the return value of sub() followed
|
|
|
|
// by the raw translation after the *match* (not captured group).
|
|
|
|
output.push(inputText.substr(0, match.index));
|
|
|
|
output.push(subs[i].apply(null, capturedGroups));
|
|
|
|
output.push(inputText.substr(match.index + match[0].length));
|
2017-05-30 14:55:21 +00:00
|
|
|
}
|
2017-05-30 15:17:42 +00:00
|
|
|
|
2017-06-12 15:45:36 +00:00
|
|
|
// this is a bit of a fudge to avoid the 'Each child in an array or iterator
|
|
|
|
// should have a unique "key" prop' error: we explicitly pass the generated
|
|
|
|
// nodes into React.createElement as children of a <span>.
|
|
|
|
return React.createElement('span', null, ...output);
|
2017-05-30 14:55:21 +00:00
|
|
|
}
|
|
|
|
|
2017-05-26 14:29:11 +00:00
|
|
|
// Allow overriding the text displayed when no translation exists
|
2017-06-01 01:04:43 +00:00
|
|
|
// Currently only used in unit tests to avoid having to load
|
2017-05-26 14:29:11 +00:00
|
|
|
// the translations in riot-web
|
|
|
|
export function setMissingEntryGenerator(f) {
|
|
|
|
counterpart.setMissingEntryGenerator(f);
|
|
|
|
}
|
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
export function setLanguage(preferredLangs) {
|
|
|
|
if (!Array.isArray(preferredLangs)) {
|
|
|
|
preferredLangs = [preferredLangs];
|
|
|
|
}
|
2017-05-23 14:16:31 +00:00
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
let langToUse;
|
|
|
|
let availLangs;
|
|
|
|
return getLangsJson().then((result) => {
|
|
|
|
availLangs = result;
|
2017-05-23 14:16:31 +00:00
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
for (let i = 0; i < preferredLangs.length; ++i) {
|
|
|
|
if (availLangs.hasOwnProperty(preferredLangs[i])) {
|
|
|
|
langToUse = preferredLangs[i];
|
2017-05-26 21:28:35 +00:00
|
|
|
break;
|
2017-05-23 14:16:31 +00:00
|
|
|
}
|
|
|
|
}
|
2017-05-25 15:45:32 +00:00
|
|
|
if (!langToUse) {
|
2017-06-01 19:02:40 +00:00
|
|
|
// Fallback to en_EN if none is found
|
2017-10-11 16:56:17 +00:00
|
|
|
langToUse = 'en';
|
2017-06-01 19:02:40 +00:00
|
|
|
console.error("Unable to find an appropriate language");
|
2017-05-23 14:16:31 +00:00
|
|
|
}
|
|
|
|
|
2017-06-01 18:46:25 +00:00
|
|
|
return getLanguage(i18nFolder + availLangs[langToUse].fileName);
|
2017-05-25 15:45:32 +00:00
|
|
|
}).then((langData) => {
|
|
|
|
counterpart.registerTranslations(langToUse, langData);
|
|
|
|
counterpart.setLocale(langToUse);
|
2017-10-29 22:53:00 +00:00
|
|
|
SettingsStore.setValue("language", null, "device", langToUse);
|
2017-05-25 15:45:32 +00:00
|
|
|
console.log("set language to " + langToUse);
|
|
|
|
|
|
|
|
// Set 'en' as fallback language:
|
2017-06-01 19:10:58 +00:00
|
|
|
if (langToUse != "en") {
|
|
|
|
return getLanguage(i18nFolder + availLangs['en'].fileName);
|
2017-05-23 14:16:31 +00:00
|
|
|
}
|
2017-05-25 15:45:32 +00:00
|
|
|
}).then((langData) => {
|
2017-06-01 19:10:58 +00:00
|
|
|
if (langData) counterpart.registerTranslations('en', langData);
|
2017-05-23 14:16:31 +00:00
|
|
|
});
|
2017-10-11 16:56:17 +00:00
|
|
|
}
|
2017-05-23 14:16:31 +00:00
|
|
|
|
2017-06-01 18:46:25 +00:00
|
|
|
export function getAllLanguagesFromJson() {
|
|
|
|
return getLangsJson().then((langsObject) => {
|
2017-10-11 16:56:17 +00:00
|
|
|
const langs = [];
|
|
|
|
for (const langKey in langsObject) {
|
2017-06-01 18:46:25 +00:00
|
|
|
if (langsObject.hasOwnProperty(langKey)) {
|
|
|
|
langs.push({
|
|
|
|
'value': langKey,
|
2017-10-11 16:56:17 +00:00
|
|
|
'label': langsObject[langKey].label,
|
2017-06-01 18:46:25 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return langs;
|
2017-05-25 15:45:32 +00:00
|
|
|
});
|
2017-05-23 14:16:31 +00:00
|
|
|
}
|
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
export function getLanguagesFromBrowser() {
|
2017-05-29 18:58:18 +00:00
|
|
|
if (navigator.languages && navigator.languages.length) return navigator.languages;
|
|
|
|
if (navigator.language) return [navigator.language];
|
2017-09-21 17:56:34 +00:00
|
|
|
return [navigator.userLanguage || "en"];
|
2017-05-29 18:58:18 +00:00
|
|
|
}
|
2017-05-23 14:16:31 +00:00
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
/**
|
|
|
|
* Turns a language string, normalises it,
|
|
|
|
* (see normalizeLanguageKey) into an array of language strings
|
|
|
|
* with fallback to generic languages
|
|
|
|
* (eg. 'pt-BR' => ['pt-br', 'pt'])
|
|
|
|
*
|
|
|
|
* @param {string} language The input language string
|
|
|
|
* @return {string[]} List of normalised languages
|
|
|
|
*/
|
2017-05-23 17:32:45 +00:00
|
|
|
export function getNormalizedLanguageKeys(language) {
|
2017-05-23 14:16:31 +00:00
|
|
|
const languageKeys = [];
|
|
|
|
const normalizedLanguage = this.normalizeLanguageKey(language);
|
|
|
|
const languageParts = normalizedLanguage.split('-');
|
2017-05-25 15:45:32 +00:00
|
|
|
if (languageParts.length == 2 && languageParts[0] == languageParts[1]) {
|
2017-05-23 14:16:31 +00:00
|
|
|
languageKeys.push(languageParts[0]);
|
|
|
|
} else {
|
|
|
|
languageKeys.push(normalizedLanguage);
|
2017-05-25 15:45:32 +00:00
|
|
|
if (languageParts.length == 2) {
|
2017-05-23 14:16:31 +00:00
|
|
|
languageKeys.push(languageParts[0]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return languageKeys;
|
2017-10-11 16:56:17 +00:00
|
|
|
}
|
2017-05-23 14:16:31 +00:00
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
/**
|
|
|
|
* Returns a language string with underscores replaced with
|
|
|
|
* hyphens, and lowercased.
|
|
|
|
*/
|
2017-05-23 17:32:45 +00:00
|
|
|
export function normalizeLanguageKey(language) {
|
2017-10-11 16:56:17 +00:00
|
|
|
return language.toLowerCase().replace("_", "-");
|
|
|
|
}
|
2017-05-25 15:45:32 +00:00
|
|
|
|
2017-05-25 18:53:27 +00:00
|
|
|
export function getCurrentLanguage() {
|
|
|
|
return counterpart.getLocale();
|
|
|
|
}
|
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
function getLangsJson() {
|
2017-08-13 00:56:37 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
request(
|
|
|
|
{ method: "GET", url: i18nFolder + 'languages.json' },
|
|
|
|
(err, response, body) => {
|
|
|
|
if (err || response.status < 200 || response.status >= 300) {
|
|
|
|
reject({err: err, response: response});
|
2017-08-24 14:42:32 +00:00
|
|
|
return;
|
2017-08-13 00:56:37 +00:00
|
|
|
}
|
|
|
|
resolve(JSON.parse(body));
|
2017-10-11 16:56:17 +00:00
|
|
|
},
|
2017-08-13 00:56:37 +00:00
|
|
|
);
|
|
|
|
});
|
2017-05-25 15:45:32 +00:00
|
|
|
}
|
|
|
|
|
2017-11-01 14:55:58 +00:00
|
|
|
function weblateToCounterpart(inTrs) {
|
|
|
|
const outTrs = {};
|
|
|
|
|
|
|
|
for (const key of Object.keys(inTrs)) {
|
|
|
|
const keyParts = key.split('|', 2);
|
|
|
|
if (keyParts.length === 2) {
|
|
|
|
let obj = outTrs[keyParts[0]];
|
|
|
|
if (obj === undefined) {
|
|
|
|
obj = {};
|
|
|
|
outTrs[keyParts[0]] = obj;
|
|
|
|
}
|
|
|
|
obj[keyParts[1]] = inTrs[key];
|
|
|
|
} else {
|
|
|
|
outTrs[key] = inTrs[key];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return outTrs;
|
|
|
|
}
|
|
|
|
|
2017-05-25 15:45:32 +00:00
|
|
|
function getLanguage(langPath) {
|
2017-08-13 00:56:37 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
request(
|
|
|
|
{ method: "GET", url: langPath },
|
|
|
|
(err, response, body) => {
|
|
|
|
if (err || response.status < 200 || response.status >= 300) {
|
|
|
|
reject({err: err, response: response});
|
2017-08-24 14:42:32 +00:00
|
|
|
return;
|
2017-08-13 00:56:37 +00:00
|
|
|
}
|
2017-11-01 14:55:58 +00:00
|
|
|
resolve(weblateToCounterpart(JSON.parse(body)));
|
2017-10-11 16:56:17 +00:00
|
|
|
},
|
2017-08-13 00:56:37 +00:00
|
|
|
);
|
|
|
|
});
|
2017-05-25 15:45:32 +00:00
|
|
|
}
|