A web-based drawing app
git clone git://soophie.de/outline
blob: 67ecea91ad4c9ab573ceef32dd616ec0de4d7fe5 (2657 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
if('localStorage' in window) {98
localStorage.setItem('outline.user.lang', code);99
}100
let elements = document.querySelectorAll('[data-lang]');101
for(let item of elements) {102
let content = lang[code][item.dataset.lang];103
if(content) {104
let type = item.dataset.type || 'content';105
let badge;106
if(item.dataset.badge === 'true') {107
badge = item.querySelector('.badge');108
}109
switch(type) {110
case 'content':111
item.textContent = content;112
if(badge) {113
item.append(badge);114
}115
break;116
case 'tooltip':117
item.dataset.title = content;118
break;119
default:120
break;121
}122
}123
}124
}125
}127
export default {128
init,129
load,130
parse,131
get_current,132
get,133
change134
};