import english from "./locales/en.js";
import portuguese from "./locales/pt-BR.js";
const CATALOGS = { en: english, "pt-BR": portuguese };
const STORAGE_KEY = "rustploy.language";
export const LANGUAGES = [
{ code: "en", label: "English" },
{ code: "pt-BR", label: "Português" },
];
function storedLanguage() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored && CATALOGS[stored] ? stored : "en";
} catch (_) {
return "en";
}
}
let store = null;
let fallbackLanguage = storedLanguage();
export function currentLanguage() {
return store ? store.locale : fallbackLanguage;
}
function lookup(source) {
const catalog = CATALOGS[currentLanguage()];
const translated = catalog ? catalog[source] : undefined;
return translated === undefined ? source : translated;
}
function fill(text, values) {
return values.length === 0 ? text : text.replace(/\{(\d+)\}/g, (placeholder, index) => (index in values ? values[index] : placeholder));
}
export function t(first, ...values) {
if (Array.isArray(first)) {
const key = first.reduce((accumulated, part, index) => accumulated + (index === 0 ? "" : `{${index - 1}}`) + part, "");
return fill(lookup(key), values);
}
return lookup(first);
}
function normalize(text) {
return text.replace(/\s+/g, " ").trim();
}
export function registerI18n(Alpine) {
Alpine.store("i18n", {
locale: fallbackLanguage,
languages: LANGUAGES,
set(code) {
if (!CATALOGS[code]) return;
this.locale = code;
document.documentElement.lang = code;
try {
localStorage.setItem(STORAGE_KEY, code);
} catch (_) {
}
},
});
store = Alpine.store("i18n");
document.documentElement.lang = store.locale;
Alpine.magic("t", () => t);
Alpine.directive("t", (element, { value: attribute }, { effect }) => {
if (attribute) {
const source = normalize(element.getAttribute(attribute) ?? "");
effect(() => element.setAttribute(attribute, lookup(source)));
return;
}
const original = element.textContent;
const leading = original.match(/^\s*/)[0];
const trailing = original.match(/\s*$/)[0];
const source = normalize(original);
effect(() => {
element.textContent = leading + lookup(source) + trailing;
});
});
}