You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
111 lines
2.8 KiB
JavaScript
111 lines
2.8 KiB
JavaScript
class Message {
|
|
constructor(messageList) {
|
|
this.messages = new Map();
|
|
this.setMessages(messageList);
|
|
}
|
|
|
|
setMessages(messageList) {
|
|
if (messageList instanceof Map) {
|
|
this.messages = messageList;
|
|
} else {
|
|
this.messages.clear();
|
|
for (let key in messageList) {
|
|
this.messages.set(key, messageList[key]);
|
|
}
|
|
}
|
|
}
|
|
|
|
localize(msgId, args) {
|
|
if (this.messages.has(msgId)) {
|
|
return this.replaceVariables(this.messages.get(msgId) || '{' + msgId + '}', args);
|
|
} else {
|
|
console.warn(`Missing localization for message id: ${msgId}`);
|
|
return '{' + msgId + '}';
|
|
}
|
|
}
|
|
|
|
localizeOrNull(msgId, args) {
|
|
if (this.messages.has(msgId)) {
|
|
return this.replaceVariables(this.messages.get(msgId) || '{' + msgId + '}', args);
|
|
} else {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
textOrNull(msgId, args) {
|
|
return this.localizeOrNull(msgId, args);
|
|
}
|
|
|
|
// Alias for compatibility
|
|
text(msgId, args) {
|
|
return this.localize(msgId, args);
|
|
}
|
|
|
|
|
|
replaceVariables(template, params = []) {
|
|
let result = template;
|
|
let paramId;
|
|
result = result.replace(/\{(\w+)\}/g, (...matches) => {
|
|
paramId = parseInt(matches[1]);
|
|
if (params[paramId]) {
|
|
return params[paramId];
|
|
} else {
|
|
return '';
|
|
}
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
static makeGlobal(messageList = []) {
|
|
window.msg = new Message(messageList);
|
|
}
|
|
}
|
|
|
|
Message.makeGlobal();
|
|
|
|
class Config {
|
|
constructor(configList) {
|
|
this.configs = new Map();
|
|
this.setConfigs(configList);
|
|
}
|
|
|
|
setConfigs(configList) {
|
|
if (configList instanceof Map) {
|
|
this.configs = configList;
|
|
} else {
|
|
this.configs.clear();
|
|
for (let key in configList) {
|
|
this.configs.set(key, configList[key]);
|
|
}
|
|
}
|
|
}
|
|
|
|
get(configId, defaultValue = null) {
|
|
if (this.configs.has(configId)) {
|
|
return this.configs.get(configId)
|
|
} else {
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
static makeGlobal(configList = []) {
|
|
window.config = new Config(configList);
|
|
}
|
|
}
|
|
|
|
Config.makeGlobal();
|
|
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
const messages = document.querySelector('script[type="application/json"][data-messages]');
|
|
if (messages) {
|
|
const messageList = JSON.parse(messages.textContent);
|
|
window.msg.setMessages(messageList);
|
|
}
|
|
|
|
const configs = document.querySelector('script[type="application/json"][data-configs]');
|
|
if (configs) {
|
|
const configList = JSON.parse(configs.textContent);
|
|
window.config.setConfigs(configList);
|
|
}
|
|
}); |