A web-based drawing app
git clone git://soophie.de/outline
blob: 703104d5316188e8986ecca171789edc9cde8e26 (2358 bytes)[doc][blame][raw]
1
const LINE_BREAK_PATTERN = /\r\n|\r|\n/;2
const PROPERTY_PATTERN = /^([\w+.-]+)=([^=]*)$/;4
let lang = {};5
let default_lang;6
let current_lang;8
/**9
Sets the default and current language.11
@function init12
@constructor13
@param {string} code - The locale code;14
*/15
function init(code) {16
default_lang = code;17
current_lang = code;18
}20
/**21
Reads all properties files in the given directory and specified locale code.23
@async24
@function load25
@param {string} path - The path to the locale files.26
@param {string[]} locales - The list containing all locales.27
@return {Object} The locale object.28
*/29
async function load(path, locales) {30
for(let code of locales) {31
let text = await fetch(`${path}/${code}.properties`)32
.then(function(response) {33
if(!response.ok) {34
throw new Error('(404) Not Found');35
}36
return response.text();37
})38
.catch(function(error) {39
console.error(`No properties file found for locale '${code}'!`, error);40
});41
if(text) {42
lang[code] = parse(text);43
}44
}45
}47
/**48
Converts properties text to a locale object.50
@function parse51
@param {string} text - Raw properties text data.52
@return {Object} The locale object.53
*/54
function parse(text) {55
let result = {};56
for(let line of text.split(LINE_BREAK_PATTERN)) {57
let match = PROPERTY_PATTERN.exec(line);58
if(match) {59
result[match[1]] = match[2];60
}61
}62
return result;63
}65
/**66
Returns the locale object by the given locale code.68
@function change69
@return {Object} The locale object.70
*/71
function get() {72
return lang[current_lang];73
}75
/**76
Changes language text from all HTMLElements with the specified datatag.78
@function change79
@param {string} code - The local code.80
*/81
function change(code) {82
if(lang[code]) {83
current_lang = code;84
let elements = document.querySelectorAll('[data-lang]');85
for(let item of elements) {86
let content = lang[code][item.dataset.lang];87
if(content) {88
let type = item.dataset.type || 'content';89
let badge;90
if(item.dataset.badge === 'true') {91
badge = item.querySelector('.badge');92
}93
switch(type) {94
case 'content':95
item.textContent = content;96
if(badge) {97
item.append(badge);98
}99
break;100
case 'tooltip':101
item.dataset.title = content;102
break;103
default:104
break;105
}106
}107
}108
}109
}111
export default { init, load, parse, get, change };