Files
acaua/apps/gui/ui/i18n.js
T
2026-11-04 20:21:33 -03:00

190 lines
7.0 KiB
JavaScript

import { EN } from './i18n-en.js';
let lang = 'pt';
export const isEn = () => lang === 'en';
export const currentLang = () => lang;
export const LOC = () => (lang === 'en' ? 'en-US' : 'pt-BR');
export function resolveLang(pref) {
if (pref === 'pt' || pref === 'en') return pref;
return (navigator.language || 'pt').toLowerCase().startsWith('pt') ? 'pt' : 'en';
}
const ATTRS = ['placeholder', 'title', 'aria-label', 'alt', 'data-empty'];
const SKIP = '.ssid, .bssid, .mono, pre, code, input, textarea, script, style, [data-i18n-skip]';
const exact = new Map(Object.entries(EN).filter(([key]) => !key.includes('{n}')));
const patterns = Object.entries(EN)
.filter(([key]) => key.includes('{n}'))
.map(([key, value]) => {
const parts = key.split('{n}').map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
return { re: new RegExp('^' + parts.join('(.+?)') + '$', 's'), to: value };
})
.sort((a, b) => b.re.source.length - a.re.source.length);
const cache = new Map();
export function tr(text) {
if (!isEn()) return text;
const lead = text.match(/^\s*/)[0];
const trail = text.match(/\s*$/)[0];
const core = text.trim();
if (!core) return text;
if (cache.has(core)) return lead + cache.get(core) + trail;
let out = exact.get(core);
if (out === undefined) {
for (const pattern of patterns) {
const match = core.match(pattern.re);
if (match) {
let index = 0;
out = pattern.to.replace(/\{n\}/g, () => tr(match[++index] ?? ''));
break;
}
}
}
if (out === undefined) out = core;
if (cache.size > 5000) cache.clear();
cache.set(core, out);
return lead + out + trail;
}
// The server speaks fixed English messages; the interface shows them in the
// user's language. Unknown messages pass through as they came.
const SERVER_MESSAGES = {
'invalid credentials': 'Credenciais inválidas.',
'too many attempts': 'Muitas tentativas.',
'setup required': 'A configuração inicial ainda não foi concluída.',
'invalid setup code': 'Código de configuração inválido.',
'the last administrator must remain': 'O último administrador precisa continuar existindo.',
'MFA is mandatory for administrators': 'O MFA é obrigatório para administradores.',
'no enrollment in progress': 'Nenhum cadastro de MFA em andamento.',
'username is already in use': 'Este nome de usuário já está em uso.',
'not found': 'Não encontrado.',
'recent authentication required': 'É preciso confirmar sua identidade de novo.',
forbidden: 'Sem permissão para esta ação.',
'internal error': 'Erro interno do serviço.',
'authentication required': 'Sua sessão terminou. Entre de novo.',
'invalid CSRF token': 'Sessão desatualizada. Recarregue a página.',
'analysis failed': 'A análise falhou. Os detalhes ficam no log do servidor.',
'password is too common': 'Esta senha é comum demais.',
'password must not repeat a single character': 'A senha não pode repetir um único caractere.',
'password must not be only digits': 'A senha não pode ter só dígitos.',
'new password must differ from the current one': 'A nova senha precisa ser diferente da atual.',
"username must not contain ':' or control characters": 'O nome de usuário não pode ter dois-pontos nem caracteres de controle.',
'username must not start or end with a space': 'O nome de usuário não pode começar nem terminar com espaço.',
'token expiry must be in the future and within 365 days': 'A validade do token precisa estar no futuro e em até 365 dias.',
'too many API tokens': 'Esta conta já tem tokens de API demais.',
};
const SERVER_PATTERNS = [
[/^password must be at least (\d+) characters$/, 'A senha precisa ter pelo menos {n} caracteres.'],
[/^password must be at most (\d+) bytes$/, 'A senha pode ter no máximo {n} bytes.'],
[/^username must have 1 to (\d+) characters$/, 'O nome de usuário precisa ter de 1 a {n} caracteres.'],
[/^token name must have 1 to (\d+) characters, without control characters$/, 'O nome do token precisa ter de 1 a {n} caracteres, sem caracteres de controle.'],
];
export function serverMessage(raw) {
const known = SERVER_MESSAGES[raw];
if (known) return tr(known);
for (const [re, template] of SERVER_PATTERNS) {
const match = String(raw).match(re);
if (match) return tr(template).replace('{n}', match[1]);
}
return raw;
}
const original = new WeakMap();
let observer = null;
function translateNode(node) {
if (node.nodeType === 3) {
if (node.parentElement?.closest(SKIP)) return;
const source = original.get(node) ?? node.nodeValue;
const translated = tr(source);
if (translated !== node.nodeValue) {
if (!original.has(node)) original.set(node, source);
node.nodeValue = translated;
}
} else if (node.nodeType === 1) {
if (node.matches?.(SKIP) && node.tagName !== 'INPUT') return;
for (const attribute of ATTRS) {
if (node.hasAttribute?.(attribute)) {
const key = `i18n-${attribute}`;
const source = node[key] ?? node.getAttribute(attribute);
const translated = tr(source);
if (translated !== node.getAttribute(attribute)) {
node[key] = source;
node.setAttribute(attribute, translated);
}
}
}
for (const child of node.childNodes) translateNode(child);
}
}
function restoreAll(root) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (original.has(node)) {
node.nodeValue = original.get(node);
original.delete(node);
}
}
root.querySelectorAll('*').forEach((element) => {
for (const attribute of ATTRS) {
const key = `i18n-${attribute}`;
if (element[key] !== undefined) {
element.setAttribute(attribute, element[key]);
delete element[key];
}
}
});
}
function start() {
translateNode(document.body);
document.title = tr(document.title);
if (observer) return;
observer = new MutationObserver((mutations) => {
observer.disconnect();
for (const mutation of mutations) {
if (mutation.type === 'childList') mutation.addedNodes.forEach(translateNode);
else if (mutation.type === 'characterData') {
original.delete(mutation.target);
translateNode(mutation.target);
} else if (mutation.type === 'attributes') {
delete mutation.target[`i18n-${mutation.attributeName}`];
translateNode(mutation.target);
}
}
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ATTRS,
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ATTRS,
});
}
function stop() {
observer?.disconnect();
observer = null;
restoreAll(document.body);
}
export function setLang(pref) {
const next = resolveLang(pref);
const changed = next !== lang;
lang = next;
document.documentElement.lang = lang === 'en' ? 'en' : 'pt-BR';
if (lang === 'en') start();
else if (changed || observer) stop();
}