A web-based drawing app
git clone git://soophie.de/outline
blob: ba4b71e0a423bb019a5f582577f98bbff94415e8 (2568 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, callback) {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
if(callback) {46
callback();47
}48
}50
/**51
Converts properties text to a locale object.53
@function parse54
@param {string} text - Raw properties text data.55
@return {Object} The locale object.56
*/57
function parse(text) {58
let result = {};59
for(let line of text.split(LINE_BREAK_PATTERN)) {60
let match = PROPERTY_PATTERN.exec(line);61
if(match) {62
result[match[1]] = match[2];63
}64
}65
return result;66
}68
/**69
Returns the current locale.71
@function get_current72
@return {string} The current locale.73
*/74
function get_current() {75
return current_lang;76
}78
/**79
Returns the locale object by the given locale code.81
@function change82
@return {Object} The locale object.83
*/84
function get() {85
return lang[current_lang];86
}88
/**89
Changes language text from all HTMLElements with the specified datatag.91
@function change92
@param {string} code - The local code.93
*/94
function change(code) {95
if(lang[code]) {96
current_lang = code;97
let elements = document.querySelectorAll('[data-lang]');98
for(let item of elements) {99
let content = lang[code][item.dataset.lang];100
if(content) {101
let type = item.dataset.type || 'content';102
let badge;103
if(item.dataset.badge === 'true') {104
badge = item.querySelector('.badge');105
}106
switch(type) {107
case 'content':108
item.textContent = content;109
if(badge) {110
item.append(badge);111
}112
break;113
case 'tooltip':114
item.dataset.title = content;115
break;116
default:117
break;118
}119
}120
}121
}122
}124
export default {125
init,126
load,127
parse,128
get_current,129
get,130
change131
};