-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtranslate.js
More file actions
45 lines (43 loc) · 1.17 KB
/
translate.js
File metadata and controls
45 lines (43 loc) · 1.17 KB
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
import { window } from './1.variables.js';
import { global } from './global.js';
import toLocale from './toLocale.js';
export default (element) => {
element = element instanceof $ ? element : $(element);
if ($.i18n) {
global('translateElement')(element);
}
return element;
};
/**
* @param {string} text text to translate
* @param {object} options
* @param {string[]} [options.args] argument array to pass to translation function
* @param {string} [options.fallback] value to return when missing or translation not loaded
* @param {string} [options.locale] locale to switch to
* @returns {string} either translated text or fallback value
*/
export function translateText(text, {
args = [],
fallback = text,
locale,
} = {}) {
if (window.$?.i18n) {
const string = `${text}`;
const val = (() => {
if (locale && $.i18n().locale !== locale) {
const temp = toLocale({
id: string,
data: args,
locale,
});
if (temp === 'ERROR') {
return string;
}
return temp;
}
return $.i18n(string, ...args);
})();
if (val !== string) return val;
}
return `${fallback}`;
}