import translations from '../translations.js'; import { state } from './state.js'; export function getTranslation(key) { const dict = translations[state.page_language] || translations["pt-BR"]; return dict[key]; } const HTML_LANG = { "pt-BR": "pt-BR", "en": "en", "zh": "zh-CN" }; const LANG_LABEL = { "pt-BR": "Português", "en": "English", "zh": "中文" }; const OG_LOCALE = { "pt-BR": "pt_BR", "en": "en_US", "zh": "zh_CN" }; const DATE_LOCALE = { "pt-BR": "pt-BR", "en": "en-US", "zh": "zh-CN" }; function setMeta(selector, value) { if (value === undefined || value === "") return; const el = document.querySelector(selector); if (el) el.setAttribute("content", value); } export function setLanguage(lang, onLanguageChanged) { state.page_language = lang; document.documentElement.lang = HTML_LANG[lang] || lang; const dict = translations[lang] || translations["pt-BR"]; if (dict.page_title) { document.title = dict.page_title; } setMeta('meta[name="description"]', dict.meta_description); setMeta('meta[property="og:title"]', dict.og_title); setMeta('meta[property="og:description"]', dict.meta_description); setMeta('meta[property="og:locale"]', OG_LOCALE[lang]); setMeta('meta[name="twitter:title"]', dict.og_title); setMeta('meta[name="twitter:description"]', dict.meta_description); document.querySelectorAll("[data-i18n]").forEach(elem => { const key = elem.getAttribute("data-i18n"); if (dict[key] !== undefined) { elem.textContent = dict[key]; } // Elements whose translation is empty (e.g. paper_lang_note in pt-BR) are hidden. if (dict[key] === "") elem.hidden = true; else if (elem.hidden && dict[key] !== undefined) elem.hidden = false; }); document.querySelectorAll("[data-i18n-placeholder]").forEach(elem => { const key = elem.getAttribute("data-i18n-placeholder"); if (dict[key] !== undefined) { elem.setAttribute("placeholder", dict[key]); } }); document.querySelectorAll("[data-i18n-aria-label]").forEach(elem => { const key = elem.getAttribute("data-i18n-aria-label"); if (dict[key] !== undefined) { elem.setAttribute("aria-label", dict[key]); } }); document.querySelectorAll("time[datetime]").forEach(elem => { try { const d = new Date(elem.getAttribute("datetime") + "T12:00:00Z"); elem.textContent = new Intl.DateTimeFormat(DATE_LOCALE[lang] || lang, { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" }).format(d); } catch (e) { /* keep existing text */ } }); updateLangMenu(lang); if (onLanguageChanged) { onLanguageChanged(); } } function updateLangMenu(lang) { const labelElem = document.querySelector("#current-lang-label"); if (labelElem && LANG_LABEL[lang]) { labelElem.textContent = LANG_LABEL[lang]; } document.querySelectorAll("#lang_dropdown button[data-lang]").forEach(btn => { if (btn.getAttribute("data-lang") === lang) { btn.setAttribute("aria-current", "true"); } else { btn.removeAttribute("aria-current"); } }); const details = document.querySelector("#lang_dropdown"); if (details) { details.removeAttribute("open"); } }