mirror of
https://forge.dns-witch.net/dns-witch/nomilo.git
synced 2026-06-25 09:42:20 +02:00
51 lines
1.5 KiB
JavaScript
51 lines
1.5 KiB
JavaScript
async function l10n(key, args = undefined) {
|
|
if (window.fluentBundle === undefined) {
|
|
const lang = document.documentElement.lang;
|
|
const bundle = new FluentBundle.FluentBundle(lang);
|
|
|
|
const promises = [...document.querySelectorAll('[data-l10n]')]
|
|
.map(link => fetch(link.href)
|
|
.then(res => res.text())
|
|
.then(data => new FluentBundle.FluentResource(data))
|
|
);
|
|
|
|
|
|
const resources = await Promise.all(promises);
|
|
|
|
for (const resource of resources) {
|
|
bundle.addResource(resource);
|
|
}
|
|
|
|
window.fluentBundle = bundle;
|
|
}
|
|
|
|
const [messageId, messageAttribute] = key.split('.')
|
|
|
|
const message = window.fluentBundle.getMessage(messageId);
|
|
|
|
if (message) {
|
|
const errors = [];
|
|
let pattern;
|
|
|
|
if (messageAttribute !== undefined) {
|
|
pattern = message.attributes[messageAttribute]
|
|
} else {
|
|
pattern = message.value;
|
|
}
|
|
|
|
if (pattern) {
|
|
const message = window.fluentBundle.formatPattern(pattern, args, errors)
|
|
if (errors.length > 0) {
|
|
for (const error of errors) {
|
|
console.error(`[localization error]: ${error}`)
|
|
}
|
|
}
|
|
return message
|
|
} else {
|
|
return messageAttribute ? `{${messageId}.${messageAttribute}}` : `{${messageId}}`;
|
|
}
|
|
} else {
|
|
return messageAttribute ? `{${messageId}.${messageAttribute}}` : `{${messageId}}`;
|
|
}
|
|
|
|
}
|