Files
iD/modules/util/locale.js
Tom MacWright 6341d4e4b5 one-shot build (#3266)
* One-shot development

* Move jsonp to module
* Tooltip -> module
* Remove d3.jsonp
* Fix tooltip lint
* Load all libs but d3 itself with require
* Add top-level brfs

* Unformat intro graph
2016-08-10 15:25:19 -07:00

50 lines
1.1 KiB
JavaScript

var translations = Object.create(null);
export var currentLocale = 'en';
export function setLocale(_) {
if (translations[_] !== undefined) {
currentLocale = _;
} else if (translations[_.split('-')[0]]) {
currentLocale = _.split('-')[0];
}
}
export function addTranslation(id, value) {
translations[id] = value;
}
/**
* Given a string identifier, try to find that string in the current
* language, and return it.
*
* @param {string} s string identifier
* @returns {string?} locale string
*/
export function t(s, o, loc) {
loc = loc || currentLocale;
var path = s.split('.').reverse();
var rep = translations[loc];
while (rep !== undefined && path.length) rep = rep[path.pop()];
if (rep !== undefined) {
if (o) for (var k in o) rep = rep.replace('{' + k + '}', o[k]);
return rep;
}
if (loc !== 'en') {
return t(s, o, 'en');
}
if (o && 'default' in o) {
return o.default;
}
var missing = 'Missing ' + loc + ' translation: ' + s;
if (typeof console !== 'undefined') console.error(missing); // eslint-disable-line
return missing;
}